Forum Moderators: coopster

Message Too Old, No Replies

Picking certain bits from a string

Kinda complicated

         

Richie0x

7:41 pm on May 5, 2004 (gmt 0)

10+ Year Member



$html = "<p align=justify><font face=arial size=2>text goes here.</font></p>";

How, using php can you check to see if a certain html tag exists in that string and manipulate the contents of the tag?

ie. Search it to see if any Font tags exist, and them manipulate the tags which have Size=2 and change them all to Size=1.

Or store a certain part of the tag, like the size attribute into a $.

Or delete certain attributes, delete the tag all together, or replace the tag with a completely different one like Img.

Netizen

8:05 pm on May 5, 2004 (gmt 0)

10+ Year Member



Try something like

$html=preg_replace('/(<font.*?size=)2(.*?<\/font>)/',${1}1${2},$html);

for the specific case you are talking about. The {} in the replacement is to distinguish the first match $1 from the replace text of "1".

Richie0x

9:16 pm on May 5, 2004 (gmt 0)

10+ Year Member



Thanks, but I get a Parse error when trying that script.

Deleting a tag is the main one I need.

I guess you'd search the line for '<font' and then delete that and everything between it and the next '>'. How?

Netizen

10:39 pm on May 5, 2004 (gmt 0)

10+ Year Member



Untested code, as usual. Try

$html=preg_replace('/(<font.*?size=)2(.*?<\/font>)/',"${1}1$2",$html);

If you want to delete tags try

$html=preg_replace('/(<font.*?>.*?<\/font>)/','',$html);

Richie0x

10:13 pm on May 7, 2004 (gmt 0)

10+ Year Member



Thanks you're very helpful :)

What about deleting a tag, but leaving one of the attributes behind?

Example the line is "<font face=arial size=2>" I want to be left with "size=2" but delete everything around it.

haxored

10:34 pm on May 7, 2004 (gmt 0)

10+ Year Member



$html=preg_replace('/<font.*(size=\d+).*>.*<\/font>)/',"$1",$html);

that should delete the entire font tag but leave the size attribute

Richie0x

12:55 pm on May 8, 2004 (gmt 0)

10+ Year Member



Thanks Haxored

That works if the attribute contains one character or word, but not if it contains many words, like an img Alt attribute for example. Is there a way to make it work for that? The amount of words in an Alt can vary though.

Netizen

10:32 am on May 9, 2004 (gmt 0)

10+ Year Member



The simplest way to extract this is if you know that values are enclosed by quotes i.e.

<img src="myimg.gif" alt="some image description here">

You can then do

$html=preg_replace('/<img.*?alt="(.*?)".*?>)/',"$1",$html);

If you don't have quotes around the value (which you should really) then it is harder but not impossible.

Richie0x

12:14 pm on May 9, 2004 (gmt 0)

10+ Year Member



Thanks Netizen that works fine :)