Php str_replace在给定字符串匹配时停止
我需要一个类似str_replace的函数(Php str_replace在给定字符串匹配时停止,php,string,replace,Php,String,Replace,我需要一个类似str_replace的函数(str_replace_dest可能),但在找到给定字符串时停止 $subject = "Hello World! Hello my friends."; $search = "Hello"; $replace = "This is"; $destination = "!"; str_replace_dest($search, $replace, $subject, $destination); //result This is World! H
str_replace_dest
可能),但在找到给定字符串时停止
$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.
PHP有这样的内置函数吗?还是我需要一个黑客方法?您必须向str\u replace函数传递额外的参数计数 编辑,尝试:
$subject = "Hello World! Hello my friends.";
$search = "Hello";
$replace = "This is";
$destination = "!";
str_replace($search, $replace, $subject, 1);
但您可以执行preg replace:
$subject = "Hello World! Hello my friends.";
$search = "/Hello/";
$replace = "This is";
$destination = "!";
$subject = preg_replace($search, $replace, $subject, 1);
第一种方法:使用
第二种方法:明确使用并传递限制:
$result = preg_replace('/\b'.preg_quote($search, '/').'\b/', $replace, $subject, 1);
第一种方法通常要快得多,但当您需要(例如)进行两次或多次替换时,它不适用。在strstrstr中使用stru replace,如下所示:
$subject = "Hello World! Hello my friends.";
$search = "Hello";
$replace = "This is";
$destination = "!";
$subject = strstr(str_replace($search, $replace, $subject), $destination, TRUE);
希望这有帮助。这里讨论的是用于设置序列数的count参数。不,它不是用于设置替换数的参数。它是一个变量,用于捕获完成了多少替换。您是否需要在特定数量的替换上停止,或者在到达文本的特定部分时是否要停止?比如:你好,世界,这是我的世界。你好,我的世界。你好xxx,这是我的xxx。你好,我的世界。或者你好xxx,这是我的世界。你好,我的世界。
$subject = "Hello World! Hello my friends.";
$search = "Hello";
$replace = "This is";
$destination = "!";
$subject = strstr(str_replace($search, $replace, $subject), $destination, TRUE);