Lewis
Lewis

Reputation: 14916

str_replace stops when given string matched

I need a function (str_replace_dest perhaps) similar to str_replace, but stop when a given string found.

$subject = "Hello World! Hello my friends.";
$search = "Hello";
$replace = "This is";
$destination = "!";

str_replace_dest($search, $replace, $subject, $destination);

//result

This is World! Hello my friends.

Does PHP have a built-in function like this? Or am I gonna need a hacky method?

Upvotes: 0

Views: 84

Answers (4)

ThatsRight
ThatsRight

Reputation: 170

Use str_replace inside strstr, like this:

$subject = "Hello World! Hello my friends.";
$search  = "Hello";
$replace = "This is";
$destination = "!";
$subject = strstr(str_replace($search, $replace, $subject), $destination, TRUE);

Upvotes: 0

Alma Do
Alma Do

Reputation: 37365

First way: use substr_replace()

$subject = "Hello World! Hello my friends.";
$search  = "Hello";
$replace = "This is";
$destination = "!";

$result = substr_replace(
   $subject, 
   $replace, 
   strpos($subject, $search), 
   strlen($search)
);

Second way: use preg_replace() and pass limit explicitly:

$result = preg_replace('/\b'.preg_quote($search, '/').'\b/', $replace, $subject, 1);

First way is in general much faster, but it isn't applicable when you'll want, for example, do two or more replacements.

Upvotes: 3

hopsoo
hopsoo

Reputation: 305

You can do preg replace though:

$subject = "Hello World! Hello my friends.";
$search = "/Hello/";
$replace = "This is";
$destination = "!";

$subject = preg_replace($search, $replace, $subject, 1);

Upvotes: 0

hopsoo
hopsoo

Reputation: 305

You have to pass additional parameter COUNT to the str_replace function edit, try:

$subject = "Hello World! Hello my friends.";
$search = "Hello";
$replace = "This is";
$destination = "!";

str_replace($search, $replace, $subject, 1);

Upvotes: -1

Related Questions