Replace only the first occurrence of a string in PHP
Question:
How to replace only the first occurrence of a string in PHP? Answer:
$originalText = 'This is my original text to convert';
$newText = preg_replace('/ /', '-', $originalText, 1);
echo $newText;
Description:
In PHP there is the str_replace
method that replaces all occurrences of a string in another string. However, if you want to replace only the first match then you can use the preg_replace
method. The preg_replace
method performs a regular expression search and replace.
Syntax:
preg_replace(
string|array $pattern,
string|array $replacement,
string|array $subject,
int $limit = -1,
int &$count = null
): string|array|null
Reference:
The preg_replace reference
Share "How to replace only the first occurrence of a string in PHP?"
Related snippets:
- Remove whitespace from the beginning and end of a string in PHP
- Locate a substring within a string in PHP
- Process CSV line in PHP
- Extract a substring from a string in PHP
- Split a string into words in PHP
- Replace spaces with dashes in PHP
- Replace only the first occurrence of a string in PHP
- Replace last occurrence of a string in a string in PHP
- Remove all attributes from HTML tags in PHP
- Remove HTML tags from a string except p, b, i and br in PHP
- Remove HTML tags from a string in PHP
Tags:
replace, change, only, first, occurrence, string, text, php, regexp, regular expression Technical term:
Replace only the first occurrence of a string in PHP