Jump to content

Regex Ignore HTML replace Text


Ryan0r

Recommended Posts

<?php

$arrayofwords = array ();
$arrayofwords[0] = "This";
$arrayofwords[1] = "text";
$arrayofwords[2] = "need";
$arrayofwords[3] = "words";

$str = 'This is my <img src="" title="This image text"> long text <a href="#">words</a> where I need to highlight words in the HTML text.';

$str = preg_replace ( "/(?!(?:[^<]+>|[^>]+<\/a>))\b(" . implode ( '|', $arrayofwords ) . ")\b/is", "<strong>\\1</strong>", $str );

echo $str;

?>

 

This example here is not fully working, how do I change the Regex so that it replaces the text that is wrapped by the <a> tag?

 

Eg: <a href="#">words</a> is not becoming <a href="#"><strong>words</strong></a> when I need it to.

 

Any ideas how to fix this?

 

Cheers!

Ryan

Link to comment
https://forums.phpfreaks.com/topic/148173-regex-ignore-html-replace-text/
Share on other sites

try

<?php

$arrayofwords = array ();
$arrayofwords[0] = "This";
$arrayofwords[1] = "text";
$arrayofwords[2] = "need";
$arrayofwords[3] = "words";

$str = 'This is my <img src="" title="This image text"> long text <a href="#">words</a> where I need to highlight words in the HTML text.';

$str = preg_replace ( "/(?!(?:[^<]+>))\b(" . implode ( '|', $arrayofwords ) . ")\b/is", "<strong>\\1</strong>", $str );

echo $str;

?>f/code]

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.