Jump to content

replacing the text and ignoring the html tag


asmith

Recommended Posts

Hi,

 

$a = '<a class="test">test</a>';

 

I need to change the test to <b>test</b>.

str_replace will put b tag inside the class attribute also while I need only the text inside the tag.

 

Someone can help me write the preg_replace of it?

 

Link to comment
Share on other sites

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 >

Link to comment
Share on other sites

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);

?>

 

Link to comment
Share on other sites

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.

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.