【问题标题】:Regex : ignore HTML Tags with preg_replace_callback正则表达式:使用 preg_replace_callback 忽略 HTML 标签
【发布时间】:2011-10-19 19:41:02
【问题描述】:

我正在尝试抓取 HTML 标签之间的所有文本(如果有),并在其上放置一个函数.. 我的意思是..我现在的代码是

$code = preg_replace_callback('/(\(\s*\')\s*(.*?)\s*(\')/',
        function($matches) {
            return strtolower($matches);
        }, $code);

现在我想要的是:

  1. 如果有HTML标签===返回HTML标签+strtolower(为标签之间的文字)。

  2. 如果没有 HTML 标签 === 返回 strtolower(所有文本)


示例: 如果我们有:

('TEST HERE this is a TEXT')

返回

('test here this is a text')

但如果使用 HTML 标签,例如

<DIV CLASS='tesT'>This IS A TEXT</DIV><Div class='Test1'>THIS is another TEXT</DIV>

返回

<DIV CLASS='tesT'>this is a text</DIV><Div class='Test1'>this is another text</DIV>

【问题讨论】:

标签: php regex preg-replace-callback


【解决方案1】:
$str = preg_replace_callback( '/(<.+?>)*(.*?)/s', 'replace', $str );

function replace( $matches ) {
    return $matches[1].strtolower( $matches[2] );
}

【讨论】:

  • 好代码,但问题是(它不会忽略。它删除它)..我的模式是(\(\s*\')(&lt;.+?&gt;)*\s*(.*?)\s*(\'),函数是:return $matches[1].$matches[2].strtolower($matches[3]).$matches[4];
  • @programmer4me 我的代码没有删除任何东西,完全按照你的意愿去做,我已经测试过了。
  • 好的,我试图让它工作,但问题是我正在使用这个代码。 $code = preg_replace_callback('/(\(\')(&lt;.+?&gt;)*(.*?)(&lt;.+?&gt;)*(\')/', function($matches){ var_dump($matches); }, $code); 此代码不起作用,匹配项不查看任何 html 标记 .. 匹配项 [2] 为空 .. 有什么问题??谢谢