+4 votes
in Programming Languages by (40.5k points)

A substring can be present in a string multiple times. I want to replace its first occurrence only with another substring. How can I replace only the first occurrence?

E.g.

I want to replace ":" with "|" in the following string:

Hello world: how are you?: I am busy: what about you?

The output should be: Hello world | how are you?: I am busy: what about you?

1 Answer

+3 votes
by (56.8k points)
selected by
 
Best answer

Since you want to replace only the first occurrence of the substring, you can use the PHP function preg_replace(). It has a parameter "limit" that can be used to set how many replacements you want in the string. If you set its value to 1, the function will change the first occurrence of the substring only.

The syntax of the function is as follows:

preg_replace(patterns, replacements, input, limit, count)

where,

patterns = the substring you want to replace as a regular expression.

replacements = new replacement substring or an array of replacement substrings

input = The string or array of strings in which replacements are being performed

limit = how many occurrences you want to replace. The default is -1, meaning all occurrences.

Here is an example to show how to use this function:

<?php

$str = "Hello world: how are you?: I am busy: what about you?";

$to_replace = "/:/";   // pattern

$replace_with = "|";

$how_many = 1;

print($str);

print("\n");

echo preg_replace($to_replace, $replace_with, $str, $how_many);

print("\n")

?>

The above code will print the following output:

Hello world: how are you?: I am busy: what about you?

Hello world| how are you?: I am busy: what about you? 


...