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
Share on other sites

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.

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.