【问题标题】:replace specific string pattern to html将特定的字符串模式替换为 html
【发布时间】:2013-02-13 10:39:15
【问题描述】:

对于我的股市聊天,我想将每个特定的字符串模式替换为 html 代码。 例如,如果我输入“b $goog 780”,我希望这个字符串被替换为:

Buy <a href="/stocks/goog">$goog</a> at 780 

如何使用 preg_replace 完成这项特定任务?

【问题讨论】:

    标签: php html string replace preg-replace


    【解决方案1】:
    $cmd='b $goog 780';
    
    if(preg_match('/^([bs])\s+?\$(\w+?)\s+?(.+)$/i',$cmd,$res))
    {
       switch($res[1])
       {
         case 'b': $cmd='buy';break;
         case 's': $cmd='sell';break;
       }
       $link=$cmd.' <a href="/stocks/'.$res[2].'">'.$res[2].'</a> at '.$res[3];
       echo $link;
    }
    

    【讨论】:

    • 看起来正是我所需要的!
    【解决方案2】:
    $stocks = array('$goog' => '<a href="/stocks/goog">$goog</a>',
                    '$apple' => '<a href="/stocks/apple">$apple</a>');
    
    // get the keys.
    $keys = array_keys($stocks);
    
    // get the values.
    $values = array_values($stocks);
    
    // replace
    foreach($keys as &$key) {
            $key = '/\b'.preg_quote($key).'\b/';
    }
    
    // input string.    
    $str = 'b $goog 780';
    
    // do the replacement using preg_replace                
    $str = preg_replace($keys,$values,$str);
    

    【讨论】:

      【解决方案3】:

      它必须是 preg_replace 吗?使用 preg_match 您可以提取字符串的组件并重新组合它们以形成您的链接:

      <?php
      $string = 'b $goog 780';
      $pattern = '/(b \$([^\s]+) (\d+))/';
      $matches = array();
      preg_match($pattern, $string, $matches);
      echo 'Buy <a href="/stocks/' . $matches[2] . '">$' . $matches[2] . '</a> at ' . $matches[3] ; // Buy <a href="/stocks/goog">$goog</a> at 780 
      

      该模式正在寻找的是字母“b”,后跟一个美元符号(\$ - 我们将美元转义,因为这是正则表达式中的一个特殊字符),然后是任何字符,直到它到达一个空格 ([^\s]+),然后是一个空格,最后是任意数量的数字 (\d+)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-22
        • 2020-03-06
        • 2023-03-25
        • 2021-06-20
        • 2013-05-04
        相关资源
        最近更新 更多