我有一个网络应用,需要解析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多个字符串)
答案 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);