【发布时间】:2016-01-08 17:51:19
【问题描述】:
我有一些代码,如果$subtitle1 的值仅包含字母或空格,则正则表达式替换可以正常工作。当$subtitle1 字符串以数字开头(例如“3rd Edition”)时,preg_replace 函数会意外工作。如果我在替换字符串中添加一个空格,那么 $subtitle1 的值可以以数字开头并且可以,但它会在“3rd Edition”中的 3 之前放置一个不需要的空格。
$raw_xml = '<property name="subtitle1" type="String">Linux is more than a shell</property>';
$subtitle1 = '3rd Edition';
$replacers = array (
'/(<property name="subtitle1" type="String">)([1-9A-Za-z ]+)(<\/property>)/' => sprintf("$1%s$3",$subtitle1), //1
'/(<property name="subtitle1" type="String">)([1-9A-Za-z ]+)(<\/property>)/' => sprintf("$1 %s$3",$subtitle1), //2
'/(<property name="subtitle1" type="String">)([1-9A-Za-z ]+)(<\/property>)/' => sprintf("$1%s$3",$subtitle1), //3
);
echo preg_replace(array_keys($replacers), array_values($replacers), $raw_xml);
//1 (when $subtitle1 = 'Third Edition', outputs: <property name="subtitle1" type="String">Third Edition</property>)
//2 (when $subtitle1 = '3rd Edition', outputs: <property name="subtitle1" type="String"> 3rd Edition</property>)
//3 (when $subtitle1 = '3rd Edition', outputs: rd Edition</property>)
如果$subtitle1 var 的类型始终是字符串,我是否可以做一些不同的事情来使其工作相同?我已经尝试过修饰符 s、U,但没有更进一步。感谢您对此的任何见解。
【问题讨论】:
标签: php regex string preg-replace