preg_replace 函数从字符串中删除空格
preg_replace function removing spaces from the string
我尝试构建一个标记系统并且它工作正常函数 preg_replace() 有问题,它从字符串中删除了不必要的空格。
例如,如果我的字符串是
Hey !
@Yosi
@Ben
空格将被删除,它将变成:
Hey!
@Yosi@Ben
似乎是因为我在 preg_replace 中的条件作为字符串包含在内。
我的代码:
$String = preg_replace ('/(\s|^)@'.$Memory['Name'][$x].'(\s|$)/', '[URL="http://'.$_SERVER['HTTP_HOST'].'/member.php?u='.$Memory['UserID'][$x].'"]@'.$Memory['Name'][$x].'[/URL]', $String);
您的正则表达式去除了所有空格,因为这是它在 (\s|^)
.
中查找的内容
在那里使用环视断言 (?<=\s|^)
和 (?=\s|$)
。
或者断言非罗嗦字符 (?<!\w)
和 (?!\w)
。
或者甚至只是将它们重新插入到您使用 </code> 和 <code>
的替换文本中。
此外,您的 preg_replace 看起来像是在循环中使用。使用 preg_replace_callback
来检查所有潜在的用户名要简单得多,例如:
$string = preg_replace_callback("/(?<!\w)@(\w+)(?!\w)/",
function($m) use ($names) {
list($asis, $name) = $m;
if ($isset($names[$name])) {
return "[URL=....]";
}
else return $asis;
},
$string
);
风格建议:避免大写变量名。 PHP 不是基本的。
我尝试构建一个标记系统并且它工作正常函数 preg_replace() 有问题,它从字符串中删除了不必要的空格。
例如,如果我的字符串是
Hey !
@Yosi
@Ben
空格将被删除,它将变成:
Hey!
@Yosi@Ben
似乎是因为我在 preg_replace 中的条件作为字符串包含在内。
我的代码:
$String = preg_replace ('/(\s|^)@'.$Memory['Name'][$x].'(\s|$)/', '[URL="http://'.$_SERVER['HTTP_HOST'].'/member.php?u='.$Memory['UserID'][$x].'"]@'.$Memory['Name'][$x].'[/URL]', $String);
您的正则表达式去除了所有空格,因为这是它在 (\s|^)
.
在那里使用环视断言
(?<=\s|^)
和(?=\s|$)
。或者断言非罗嗦字符
(?<!\w)
和(?!\w)
。或者甚至只是将它们重新插入到您使用
</code> 和 <code>
的替换文本中。
此外,您的 preg_replace 看起来像是在循环中使用。使用 preg_replace_callback
来检查所有潜在的用户名要简单得多,例如:
$string = preg_replace_callback("/(?<!\w)@(\w+)(?!\w)/",
function($m) use ($names) {
list($asis, $name) = $m;
if ($isset($names[$name])) {
return "[URL=....]";
}
else return $asis;
},
$string
);
风格建议:避免大写变量名。 PHP 不是基本的。