【问题标题】:PHP preg_replace words in array but skip links (href) [duplicate]PHP preg_replace 数组中的单词但跳过链接(href)[重复]
【发布时间】:2020-02-10 21:46:31
【问题描述】:

我正在编写一些代码来替换 WordPress 内容中的单词以获取链接。例如:文本链接需要替换“example”一词:<a href="'.$site.'/glossary/example/" class="glossary-link">example</a>

我已经使用以下代码完成了这项工作:

function word_replace($text){
    $site = esc_url( home_url() );

    $replace = array(
        'example' => '<a href="'.$site.'/glossary/example/" class="glossary-link">example</a>',
        'word' => '<a href="'.$site.'/glossary/word/" class="glossary-link">word</a>',
    );

    $text = str_replace(array_keys($replace), $replace, $text);

    return $text;
}

唯一的问题是 href="" 属性中的单词也会被替换,这会破坏 HTML。如何避免在 href="" 属性或 class="" 属性中替换单词?我需要什么正则表达式来跳过这些属性?一段示例代码将是一个很大的帮助:-)

【问题讨论】:

  • php regex to match outside of html tags 的可能重复项。如果您想通过正则表达式执行此操作,我建议您使用this answer
  • 嗨@bobblebubble,感谢您回答我的问题以及此解决方案的链接。我实际上正在寻找与此相反的答案。在此评论 (stackoverflow.com/a/7891998/7735516) 中,除了链接(HTML a 标签)外,所有内容都被跳过。我想替换 WordPress 内容 ($text) 内的数组中的任何单词,但跳过 HTML a 标签。我如何做到这一点?
  • 你的意思是外部标签,对吧?见this at regex101。如果不是 &lt;inside&gt;,它匹配 foobar

标签: php regex wordpress replace preg-replace


【解决方案1】:

试试这个

$site = 'http://example.com';
$html = '<a href="'.$site.'text">Link</a>';
$dom = new DomDocument;
$dom->loadHTML($html);
$nodes = $dom->getElementsByTagName('a');
$node = $nodes[0];
$node->setAttribute('href', 'page.html');
echo $dom->saveHTML($node);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-11
    • 2012-01-19
    • 1970-01-01
    • 1970-01-01
    • 2020-02-23
    • 2017-10-10
    • 1970-01-01
    • 2023-04-11
    相关资源
    最近更新 更多