- Instant help with your Php coding problems

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
Share "How to replace only the first occurrence of a string in PHP?"