正则表达式从PHP中删除'%i'和类似的字符串?

时间:2013-05-31 18:34:24

标签: php regex

我有一个网络应用,需要解析iOS应用中的字符串文件。我试图在字符串中找到Objective-C样式百分比转义的所有实例,并在PHP中为它们添加一个span类。例如,

"Hello my name is %@ and I have %ld cats"

应该成为:

"Hello my name is <span class='b'>%@</span> and I have <span class='b'>%ld</span> cats"

不幸的是,我的正则表达式技巧已经过时了。我该如何正确有效地完成这项工作? (可能一次解析1000多个字符串)

1 个答案:

答案 0 :(得分:3)

也许......

$string = "Hello my name is %@ and I have %ld cats";
$pattern = "/(%[^\s]+)/";
$replacedStr = preg_replace($pattern, "<span class='b'>$1</span>", $string);

根据NullUserException,这也会起作用(实际上更短!):

$string = "Hello my name is %@ and I have %ld cats";
$pattern = "/%\S+/";
$replacedStr = preg_replace($pattern, "<span class='b'>$0</span>", $string);