Reputation: 14916
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
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
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
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
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