现有xml文件内容如下:
...35$35.00Kindex.php?module=Opportunities&action=index&query=true&searchFormTab=advanced_search&lead_source=Prospecting0$0.00Kindex.php?module=Opportunities&action=index&query=true&searchFormTab=advanced_search&lead_source=&sales_stage=ProspectingQualification0$0.00Kindex.php?module=Opportunities&action=index&query=true&searchFormTab=advanced_search&lead_source=&sales_stage=Qualification....
有如下一段方法,处理xml的,替换节点link的内容,将里面的链接内容用urlencode编码:
function processXML($xmlFile) {if(!file_exists($xmlFile)) {$GLOBALS['log']->debug("Cannot open file ($xmlFile)");}$pattern = array();$replacement = array();$content = file_get_contents($xmlFile);$content = $GLOBALS['locale']->translateCharset($content,'UTF-16LE', 'UTF-8'); //这行有问题$pattern[] = '/\([a-zA-Z0-9#?&%.;\[\]\/=+_-\s]+)\/e';$replacement[] = "''.urlencode(\"$1\").''";return preg_replace($pattern,$replacement, $content);}
上面代码的正则表达式在php5.4中是可以的,但是5.5以上版本取消了e参数。我尝试用preg_replace_callback改写,但失败了,preg_replace_callback的代码如下:
$content = preg_replace_callback('|([a-zA-Z0-9#?&%.;\[\]\/=+_-\s]+)|',function ($matches) {$u = urlencode($matches[1]);return "".$u."";},$content);
运行是有如下错误:Warning: preg_replace_callback(): Compilation failed: invalid range in character class at offset 34
该怎么修改呢,系统环境是php5.6.21
回复讨论(解决方案)
$content = preg_replace_callback( '/\(.+?)\/', function ($matches) { return "".urlencode($matches[1]).""; }, $content );
$content = preg_replace_callback( '/\(.+?)\/', function ($matches) { return "".urlencode($matches[1]).""; }, $content ); 试了下,没匹配到...同样的正则,我在那种在线正则测试网页上试了是可以的,但是php的这个方法就不行
测试了你的代码,并没有发现不对的地方
可能是你贴错了吧
测试了你的代码,并没有发现不对的地方
可能是你贴错了吧
你那php多少版本,内容都对的,一直没成功
php5.4.31 和 php5.6.13 ,测试了,都没有问题
我测试的你贴出的代码,不排除你在粘贴前有非法字符被 CSDN 吃掉了
不过你的
'|([a-zA-Z0-9#?&%.;\[\]\/=+_ -\s]+)|'
确实写的不对!
- 在方括号中表示区间,如果是 - 这个字符,应该将其写在最
Compilation failed: invalid range in character class 编译失败:字符类中无效的范围
\s 可表示 空格、制表符、回车、换行
那么 _-\s 应表示一个什么样的字符区间呢?
本文原创发布php中文网,转载请注明出处,感谢您的尊重!