Naim Berk Tumer
Naim Berk Tumer

Reputation: 129

Replace a character between two words

I have a string like blah blah [START]Hello-World[END] blah blah.

I want to replace - with , between [START] and [END].

So the result should be blah blah[START]Hello,World[END] blah blah.

Upvotes: 1

Views: 58

Answers (2)

trincot
trincot

Reputation: 350272

I would suggest to use preg_replace_callback:

$string = "blah-blah [START]Hello-World. How-are-you?[END] blah-blah" .
          " [START]More-text here, [END] end of-message";
$string = preg_replace_callback('/(\[START\])(.*?)(\[END\])/', function($matches) {
    return $matches[1] . str_replace("-", ",", $matches[2]). $matches[3];
}, $string);

echo $string;

Output:

blah-blah [START]Hello,World. How,are,you?[END] blah-blah [START]More,text here, [END] end of-message

The idea of the regular expression is to get three parts: "START", "END" and the part between it. The function passes these three text fragments to the callback function, which performs a simple str_replace of the middle part, and returns the three fragments.

This way you are sure that the replacements will happen not only for the first occurrence (of the hyphen or whatever character you replace), but for every occurrence of it.

Upvotes: 1

Chin Leung
Chin Leung

Reputation: 14921

You will have to use regular expressions to accomplish what you need

$string = "blah blah [START]Hello-World[END] blah blah";
$string = preg_replace('/\[START\](.*)-(.*)\[END\]/', '[START]$1,$2[END]', $string));

Here's what the regular expression does:

\[START\] The backslash is needed to escape the square brackets. It also tells the preg_replace to look in the string where it starts with [START].

(.*) This will capture anything after the [START] and will be referenced later on as $1.

- This will capture the character you want to replace, in our case, the dash.

(.*) This will target anything after the dash and be referenced as $2 later on.

\[END\] Look for the [END] to end the regex.

Now as for the replace part [START]$1,$2[END], this will replace the string it found with the regular expression where the $1 and $2 is the references we got from earlier.

The var_dump of $string would be:

string(43) "blah blah [START]Hello,World[END] blah blah"

Upvotes: 0

Related Questions