如何在php中替换文本而不考虑单词之间的空格
我想知道,如何才能在不受空格影响的情况下用其他内容替换文本。如何在php中替换文本而不考虑单词之间的空格,php,Php,我想知道,如何才能在不受空格影响的情况下用其他内容替换文本。 (“嗨,我在这里!”将替换为“再见”) 像这样(Value==>ReplacedValue): 现在使用str\u-ireplace(str\u-ireplace(“TheOriginalWord”,“Thereslacement”,“$data”))不会做我想做的事,它会这样做: Hi, I'm here! ==> bye Hi, I'm here! ==>
(
“嗨,我在这里!”将替换为“再见”
)
像这样(
Value==>ReplacedValue
):现在使用
str\u-ireplace
(str\u-ireplace(“TheOriginalWord”,“Thereslacement”,“$data”)
)不会做我想做的事,它会这样做:
Hi, I'm here! ==> bye
Hi, I'm here! ==> Hi, I'm here!
Hi , I'm here! ==> Hi , I'm here!
使用正则表达式
preg_replace('/Hi\s*,\s*I\'m\s*here!/i', "bye", $data);
\s*
匹配零个或多个空格。如果您只想匹配一个或多个空格,请改用\s+
。Barmar的答案很好,但如果您需要可重用的东西,您可以使用以下功能:
function replace_spaceless(string $subject, string $from, string $to): string
{
$pattern = '/' . preg_replace('/(?<!^)\s*\b\s*(?!$)/', '\\s*', preg_quote($from, '/')) . '/';
return preg_replace($pattern, $to, $subject);
}
function replace_spaceless(字符串$subject,字符串$from,字符串$to):字符串
{
$pattern='/'.preg_replace('/(?使用preg_replace()
),然后您可以使用与可变数量的空格匹配的模式。Hi,I'mhere!
也会被替换吗?@kerbholz是的,它可以先删除所有空格,或者使用Barmar的preg_replace()
它返回一个错误警告:preg_replace():在第132行的file.php中找不到结尾分隔符“!”,需要转义字符串中的“
。但您应该因为引号问题而得到语法错误,而不是该错误。
function replace_spaceless(string $subject, string $from, string $to): string
{
$pattern = '/' . preg_replace('/(?<!^)\s*\b\s*(?!$)/', '\\s*', preg_quote($from, '/')) . '/';
return preg_replace($pattern, $to, $subject);
}