1

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

"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 多个字符串)

4

1 回答 1

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);
于 2013-05-31T18:40:54.920 回答