Jump to content

Find replace based on HTML Tag in PHP


natasha_thomas

Recommended Posts

 

Folks,

 

I need to Find and Replace some words in Source HTML, which is saved in a PHP Variable.

 

Example:

 

$html = '<img src="some_source" title="paintball mask Picture" alt="Image for Paintball Mask"> <strong> Best Paintball Mask</strong>';

 

Find Condition: I want to FInd word "Paintball Mask" in vairiable $html, only where if the word "Paintball Mask" is there in Htaml Tag <Strong> </Strong>.  As you can observe in $html, we have "Paintball Mask" in <IMG> Tag also, i want to Skip this because I only Need to COnsider if the word "Paintball Mask" there in <strong></strong> or not.

 

 

One the words is found in <strong></strong> tag, i need to replace that word, to make it a hyperlink. (I think this bit can be done with strreplace())

 

But how can i restict my search to only <strong></strong> tag?

 

 

 

Let me give Data Again:

 

$html = '<img src="some_source" title="paintball mask Picture" alt="Image for Paintball Mask"> <strong> Best Paintball Mask</strong>';

 

Find What: Paintball Mask

 

Find in Which Tag: <strong> </strong>

 

Replace it with: <a href="/">Paintball Mask</a>

 

 

can someone help me with the code?

 

Cheers

Natasha Thomas

Link to comment
https://forums.phpfreaks.com/topic/232963-find-replace-based-on-html-tag-in-php/
Share on other sites

You can use preg_replace() with a single expression for the whole thing:

 

$html = preg_replace('/(<strong>.*?)(Paintball Mask)(.*?<\/strong>)/', '$1<a href="...">$2</a>$3', $html);

 

Mr Adam,

 

What is $1, $2, $3 in the above code, what is their purpose?

 

Natasha

In the first parameter, parentheses () are used to match certain parts of the string, which are stored as back-references for use within the second parameter. These are then retrieved as the $1, $2 and $3 variables. Unlike normal variables though, you don't need to use double-quotes for them to be parsed. FYI you could also use \1, \2, \3. So in this case:

 

(<strong>.*?) = $1

(Paintball Mask) = $2

(.*?<\/strong>) = $3

 

If there were any more used, they'd carry on into $4, $5, $6, etc.

 

The manual explains all this, I'd recommend having a good read.

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.