dongtao9095 2014-05-11 13:42
浏览 28
已采纳

PHP:带有模式数组的preg_replace [关闭]

I would like to replace the value of my variable $os with the preg_replace function, where I have an array of multiple regex patterns to be searched from and and array of multiple replacements to replace with. If $pattern_os[0] matches $os, it shall also be replaced with the corresponding $replace_os[0].

Here is my code:

<?php
    $useragent = $_SERVER['HTTP_USER_AGENT'];
    $pattern_os = array('/.*Mac.*/','/.*Windows.*/');
    $replace_os = array('Mac','Windows');
    $os = $useragent;
    $no_os = "No operating system was found. <br />";

    for($i=0;$i<2;$i++){
        preg_replace($pattern_os[$i], $replace_os[$i], $os);
    }

    echo $os;
?>

This is the output I get:

Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/7.0.3 Safari/537.75.14

Of course I'd like to have an output like this:

Mac

It'd be nice if someone could help me with this problem.

I'm new here, frustrated after failing so many times and this is my first question, so telling me what to improve on asking or where to search (although I think I spent enough time googling) might also help a bit.

Thanks

  • 写回答

1条回答 默认 最新

  • dongqi6964 2014-05-11 13:50
    关注

    You're not assigning the result of the preg_replace to a variable. You keep inputting, and not changing, $os.

    This should work:

    for ( $i=0; $i<2; $i++ ) {
        $os = preg_replace($pattern_os[$i], $replace_os[$i], $os);
    }
    

    and of course you could use foreach:

    foreach ( $pattern_os as $i => $pattern ) {
        $os = preg_replace($pattern, $replace_os[$i], $os);
    }
    

    or at least count instead of 2:

    for ( $i=0; $i<count($pattern_os); $i++ ) {
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 hexo+github部署博客
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?