PHP stru_替换;检查有无超过更换零件的数量
假设我有以下代码:PHP stru_替换;检查有无超过更换零件的数量,php,string,replace,str-replace,Php,String,Replace,Str Replace,假设我有以下代码: $string = "Hello! This is a test. Hello this is a test!" echo str_replace("Hello", "Bye", $string); 这将用Bye替换$string中的所有Hello。例如,如何排除存在的所有内容在你好之后 意思是,我想要这个输出:Hello!这是一个测试。再见,这是一个测试 php中有没有办法做到这一点?使用带有特定正则表达式模式的preg\u repalce函数的解决方案: $strin
$string = "Hello! This is a test. Hello this is a test!"
echo str_replace("Hello", "Bye", $string);
这将用Bye
替换$string
中的所有Hello
。例如,如何排除存在的所有内容代码>在你好
之后
意思是,我想要这个输出:Hello!这是一个测试。再见,这是一个测试代码>
php中有没有办法做到这一点?使用带有特定正则表达式模式的preg\u repalce
函数的解决方案:
$string = "Hello! This is a test. Hello this is a test!";
$result = preg_replace("/Hello(?!\!)/", "Bye", $string);
print_r($result);
输出:
Hello! This is a test. Bye this is a test!
(?!\!)
-先行否定断言,仅当单词后面没有“!”时才匹配Hello
word 使用带有特定正则表达式模式的preg\u repalce
函数的解决方案:
$string = "Hello! This is a test. Hello this is a test!";
$result = preg_replace("/Hello(?!\!)/", "Bye", $string);
print_r($result);
输出:
Hello! This is a test. Bye this is a test!
(?!\!)
-先行否定断言,仅当单词后面没有“!”时才匹配Hello
word 您需要一个正则表达式:
echo preg_replace("/Hello([^!])/", "Bye$1", $string);
[]
是一个字符类,^
表示不是。所以Hello
后面没有代码>。在()
中捕获非
位于Hello
之后,因此您可以在替换中使用它作为$1
(第一个捕获组)。您需要一个正则表达式:
echo preg_replace("/Hello([^!])/", "Bye$1", $string);
[]
是一个字符类,^
表示不是。所以Hello
后面没有代码>。在()
中捕获非
位于Hello
之后,因此您可以在替换中使用它作为$1
(第一个捕获组)