Jump to content

replacing the text and ignoring the html tag


asmith

Recommended Posts

Thanks for the reply mate ^^

 

I guess by your code $a will be <b>test</b>.  While I needed it to be <a class="test"><b>test</b></a>

 

I'm sorry i said a wrong example.

I need to go through an HTML code and check the text only and ignore the tags attributes (Everything that is not inside < and >):

 

<?php

$content = '<a class="text">text</a> This is some text and other elements <b class="text">Goes here</b>'; // html content

$check = 'text';
?>

 

Find $check and make it bold in the html but ignore checking whatever that is between < and >

My last try was something like this: (Which confused me as well)

 

<?php

$content = preg_replace('~^(<(.*)^>)(.*)^(^<(.*)>)~','<b>$1</b>', $content);

?>

 

or

 

 

<?php

$content = preg_replace('~^(<(.*)^>)('.$check.')^(^<(.*)>)~','<b>'.$check.'</b>', $content);

?>

 

Ok, Getting close.

 

Daniel0 your code showed a blank screen to me. But sure it gave me the idea. I modified your code to this and its working. But please correct me if I'm wrong or if this code will fail in some cases?

 

<?php
$content = preg_replace('~(<[^>]+>)?' . preg_quote($check, '~') . '(</[^>]+>)?~', '$1<b>'.$check.'</b>$2', $content);
?>

 

(<[^>]+>)? :  The question mark for the times the text is not in any tag. just appearing as content.

 

EDIT: It fails and makes the example like this :

<a class="text"><b>text</b></a> This is some <b>text</b> and other elements <b class="<b>text</b>">Goes here</b>

 

it ignores the a tag, but it fails at the b tag.

 

 

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.