【问题标题】:Regex fix for preg_replace_callback functionpreg_replace_callback 函数的正则表达式修复
【发布时间】:2011-11-16 11:40:22
【问题描述】:

字符串:

$string = '{$string#anything#something this string will output default |ucfirst|strtoupper}';

PREG_REPLACE_CALLBACK 代码(PHP):

$string = preg_replace_callback('/\{\$?([^# ]+)\#?([^ ]+)? ?([^|]+)?[ \|]?([^\}]+)?\}/', $matches, $string);

输出($matches):

Array
(
    [0] => {$string#anything#something can you hear me? |ucfirst|ucfirst|ucfirst|strtoupper}
    [1] => string
    [2] => anything#something
    [3] => can you hear me? 
    [4] => ucfirst|strtoupper
)

要求:代替{$string this string will output default |ucfirst|strtoupper},我想使用{$string this string will output default ucfirst|strtoupper}(注意:ucfirst前面的管道符号被删除);

重要提示:输出(即 $matches 数组)应该与上面打印的相同。

非常感谢您的帮助,感谢您的阅读。

【问题讨论】:

    标签: php regex preg-replace-callback


    【解决方案1】:

    我尝试了你的代码来改变你的功能......

    代码

     <pre>
     <?php
          $string = '{$string#anything#something this string will output default |ucfirst|strtoupper}'; http://www.magentocommerce.com/support/magento_core_api 
          preg_match('/\{\$?([^# ]+)\#?([^ ]+)? ?([^|]+)?[ \|]?([^\}]+)?\}/', $string, $matches);
          var_dump($matches);
      ?>
      </pre>
    

    获得的结果

    array(5) {
        [0]=>string(80) "{$string#anything#something this string will output default |ucfirst|strtoupper}"
        [1]=>string(6) "string"
        [2]=>string(18) "anything#something"
        [3]=>string(32) "this string will output default "
       http://php.net/manual/en/function.preg-replace-callback.php [4]=>string(18) "ucfirst|strtoupper"
    }
    

    符合你的预期吗?我们是否应该将“这个字符串将输出”默认替换为“你能听到我吗?” 你想在ucfirst之前删除到管道你想在字符串中执行此操作并更新reg exp,如果是这样,识别''ucfirst''字符串的规则是什么(第一个管道之前的最后一个字符串? )

    你想用 preg_replace_callback 做什么,这个函数将为找到的每个主题调用一个函数(你的 $matches 参数)......这是你的想法吗?

    链接文档:http://php.net/manual/en/function.preg-replace-callback.php

    【讨论】:

      猜你喜欢
      • 2011-01-26
      • 2010-12-26
      • 1970-01-01
      • 2013-12-09
      • 2013-03-22
      • 1970-01-01
      • 2022-11-14
      • 2012-07-15
      • 1970-01-01
      相关资源
      最近更新 更多