【问题标题】:preg_match between textarea in string in phpphp中字符串中textarea之间的preg_match
【发布时间】:2014-04-15 20:08:05
【问题描述】:
preg_match("/ [>](.*)[<] /", '<textarea width="500" >web scripting language of choice.</textarea>',$matches);
print_r ($matches);

我只想返回“选择的网络脚本语言”。形成这个字符串。 请帮我。 到达这个 PHP

【问题讨论】:

  • 使用 DOM 解析器而不是正则表达式。
  • / 分隔符后删除空格或添加 x。

标签: php regex html-parsing


【解决方案1】:

使用 DOM 解析器

HTML 不是常规语言,无法使用正则表达式正确解析。请改用 DOM 解析器。下面是使用 PHP 的 DOMDocument 类的方法:

$html = <<<HTML
<textarea width="500" >web scripting language of choice.</textarea>
HTML;

$dom = new DOMDocument;
$dom->loadHTML($html);
foreach ($dom->getElementsByTagName('textarea') as $tag) {
    var_dump($tag->nodeValue);
}

使用正则表达式

如果您绝对确定标记的格式会保持一致,那么正则表达式也可能会起作用。要修复您的正则表达式,请从模式中删除多余的空格:

preg_match("/[>](.*?)[<]/", $html, $matches);
var_dump($matches[1]);

输出:

string(33) "web scripting language of choice."

Demo

【讨论】:

    【解决方案2】:

    请改用strip_tags

    var_dump(strip_tags('<textarea width="500" >web scripting language of choice.</textarea>'));
    

    【讨论】:

    • 我不知道strip_tags 内部是否使用正则表达式,但这可能比preg_match 更具性能
    【解决方案3】:

    这样就可以了:

    <?
    $string = '<textarea width="500" >web scripting language of choice.</textarea>';
    
    $match = preg_replace('%<textarea width="500" >(.*?)</textarea>%i', '$1', $string );
    
    echo $match;
    //web scripting language of choice.
    ?>
    

    【讨论】:

    • 正则表达式对于这个问题来说太过分了。 strip_tags 会做得很好。
    猜你喜欢
    • 2012-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-15
    • 2012-12-07
    相关资源
    最近更新 更多