[SOLVED] - Getting n chars from a string containing tags

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
anjanesh
DevNet Resident
Posts: 1679
Joined: Sat Dec 06, 2003 9:52 pm
Location: Mumbai, India

[SOLVED] - Getting n chars from a string containing tags

Post by anjanesh »

How do I accomplish this ?

Code: Select all

<?php
$str="<FONT COLOR=maroon>1234567890</FONT>";
echo substr($str,0,5);
?>
The output is <FONT
The output should be 12345 in maroon colour.
Last edited by anjanesh on Sun Aug 22, 2004 11:28 pm, edited 1 time in total.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Code: Select all

echo substr(strip_tags($str),0,5);
User avatar
anjanesh
DevNet Resident
Posts: 1679
Joined: Sat Dec 06, 2003 9:52 pm
Location: Mumbai, India

Post by anjanesh »

This will not output in maroon colour.
The resultant string should be $str="<FONT COLOR=maroon>12345</FONT>";
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

what have you tried, other than substr? maybe some regex?
User avatar
anjanesh
DevNet Resident
Posts: 1679
Joined: Sat Dec 06, 2003 9:52 pm
Location: Mumbai, India

Post by anjanesh »

No I just have substr in the code.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

instead of just giving you the answer, I'm going to nudge you in the direction of at least 1 solution..

using the regular expression replacement functions, you can capture the substring you wish.. then call the same function again with a different pattern and replacement to convert the original string into a receptical for the substring.
User avatar
anjanesh
DevNet Resident
Posts: 1679
Joined: Sat Dec 06, 2003 9:52 pm
Location: Mumbai, India

Post by anjanesh »

Thanks. I was thinking there was a simpler way to have this done in substr - thats all.
Thanks
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

it's not possible with the substr function by itself, without exacting knowledge of the composition of the string.. you'd need to either analyze the string to see where the tag(s) start and end to find the 5 contained characters, or do as I did for the solution, use regex to just pull the data out of the string.. the solution I cooked up is fairly simple..
Post Reply