【问题标题】:Pattern for preg_replace function PHPpreg_replace 函数 PHP 的模式
【发布时间】:2018-03-25 18:34:01
【问题描述】:

我有带有 span 标签的字符串。我需要删除所有跨度 class="reference" 标记。我使用以下代码删除字符串部分。字符串部分中的部分数据代码可能会有所不同。

$string = 'Some text <span class="reference" data-code="Z22">Data code</span>';
$pattern = "|(?<=<span class=\"reference\" data-code=\"Z22\">)(.*?)(?=<\/span>)|";
$replace = '<a href=""> replaced </a>';

$matches = array();
preg_match_all($pattern, $string, $matches);

foreach ($matches[0] as $value) {
    $string = str_replace($value, $replace, $string);
}

回声 $string;

如果 data-code="will be variable",如何为这个脚本设置 $pattern

【问题讨论】:

    标签: php preg-replace preg-match


    【解决方案1】:

    data-code 位于(?&lt;= 的正后方。如果你想让 value 变量你可以阅读这个关于Variable-Width Lookbehind vs. Infinite-Width Lookbehind的答案。

    但不建议parse html with regex

    你可以做的是使用像PHP Simple HTML DOM Parser 这样的库并修改你的html。

    例如:

    include_once ("simple_html_dom.php");
    
    $data = <<<DATA
    Some text <span class="reference" data-code="Z22">Data code</span>
    DATA;
    
    $html = str_get_html($data);
    $ret = $html->find("span[class=reference]");
    foreach ($ret as $node) {
        $node->innertext = '';
    }
    echo $html->save();
    

    这会给你:

    Some text <span class="reference" data-code="Z22"></span>
    

    【讨论】:

      猜你喜欢
      • 2015-06-02
      • 1970-01-01
      • 2014-06-19
      • 2015-07-05
      • 2016-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多