dspv70887 2015-07-07 09:09
浏览 42
已采纳

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

I have this function which searches for strings like this:

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

function:

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

and change the number to its half (n/2). So far so good.

But I need to add a conditional to check if the number has more than 10 digits, if true then makes the change, if not, doesn't.

I tried this, but nope...all instances de '4444' get removed

$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条回答 默认 最新

  • dpthuyh1678 2015-07-07 10:45
    关注

    Just move the return outside the if block:

    $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
    ";
    

    Output:

    response = <unique>342342342</unique>
    <unique>26726726726727180</unique>
    <unique>4444</unique>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 系统 24h2 专业工作站版,浏览文件夹的图库,视频,图片之类的怎样删除?
  • ¥15 怎么把512还原为520格式
  • ¥15 MATLAB的动态模态分解出现错误,以CFX非定常模拟结果为快照
  • ¥15 求高通平台Softsim调试经验
  • ¥15 canal如何实现将mysql多张表(月表)采集入库到目标表中(一张表)?
  • ¥15 wpf ScrollViewer实现冻结左侧宽度w范围内的视图
  • ¥15 栅极驱动低侧烧毁MOSFET
  • ¥30 写segy数据时出错3
  • ¥100 linux下qt运行QCefView demo报错
  • ¥50 F1C100S下的红外解码IR_RX驱动问题