有条件的查找和替换php函数

时间:2015-07-07 09:09:26

标签: php find preg-replace

我有这个函数来搜索这样的字符串:

<unique>342342342</unique>
<unique>5345345345345435345</unique>
<unique>4444</unique>

功能:

$pattern = '/<unique>(.*?)<\/unique>/';
$response = preg_replace_callback($pattern,function($match){
    $value = intval(trim($match[1])/200);
    return '<unique>'.$value.'</unique>';
},$xml);

并将数字更改为其一半(n / 2)。到目前为止一切都很好。

但是我需要添加一个条件来检查数字是否超过10位数,如果为真,则进行更改,如果不是,则不进行更改。

我尝试了这个,但是没有...所有实例de'4444'被删除

$pattern = '/<unique>(.*?)<\/unique>/';
$response = preg_replace_callback($pattern,function($match){

        $valueunique = trim($match[1]);
        if(strlen($valueunique) >= 11){
            $value = intval($valueunique/200);
            return '<unique>'.$value.'</unique>';
            }
},$xml);

1 个答案:

答案 0 :(得分:1)

只需将返回移到if块之外:

$xml = '<unique>342342342</unique>
<unique>5345345345345435345</unique>
<unique>4444</unique>';

$pattern = '/<unique>(.*?)<\/unique>/';
$response = preg_replace_callback($pattern,function($match){
        $value = trim($match[1]);
        if(strlen($value) >= 11){
            $value = intval($value/200);
        }
        return '<unique>'.$value.'</unique>';
},$xml);

echo "response = $response\n";

<强>输出:

response = <unique>342342342</unique>
<unique>26726726726727180</unique>
<unique>4444</unique>
相关问题