【问题标题】:preg_match_all to find a string that may contain some html tags?preg_match_all 查找可能包含一些 html 标签的字符串?
【发布时间】:2016-05-03 08:58:15
【问题描述】:

我的博客文章有一个功能,访问者可以选择其中的一部分并留下反馈。反馈的主题是选择:它可以是几个词,也可以是一个带有一些 html 标记的短语(不一定围绕它)。

到目前为止,我的功能如下:

function enco_str_replace_nth( $search, $replace, $subject, $nth = 0 ) {

    $found = preg_match_all( '/' . preg_quote( $search ) . '/', $subject, $matches, PREG_OFFSET_CAPTURE );

    if (false !== $found && $found > $nth) {
        return substr_replace( $subject, $replace, $matches[0][$nth][1], strlen( $search ) );
    }

    return $subject;
}

当没有 HTML 标签时它确实有效。

a completely organic product

但会显示一个警告:preg_match_all(): Unknown modifier,并且在其中包含 HTML 时不起作用。

MSM is a  <strong>natural nutrient</strong>

because <em>it matters</em> to all of us

知道我应该在这个 preg_match_all 中改变什么吗?

【问题讨论】:

  • 只使用其他分隔符(例如~),问题是/没有转义。

标签: php regex preg-replace preg-match


【解决方案1】:

除了我的评论:

function enco_str_replace_nth( $search, $replace, $subject, $nth = 0 ) {
    $found = preg_match_all( '~' . preg_quote( $search ) . '~', $subject, $matches, PREG_OFFSET_CAPTURE );

    if (false !== $found && $found > $nth) {
        return substr_replace( $subject, $replace, $matches[0][$nth][1], strlen( $search ) );
    }

    return $subject;
}

【讨论】:

  • 它不再显示警告,但与此编辑也不匹配。我还尝试使用 # .. # 作为分隔符。
  • @Lazhar:那你能提供一些$search$subject 字符串吗?
猜你喜欢
  • 2014-11-14
  • 2011-05-30
  • 1970-01-01
  • 2011-01-10
  • 1970-01-01
  • 1970-01-01
  • 2023-01-31
  • 2011-05-08
  • 1970-01-01
相关资源
最近更新 更多