EchoFool Posted July 17, 2010 Share Posted July 17, 2010 Hey, How would you do a replacement on a string which changes ? For example: <a href="users.php?id=3">Username</a> How would you use str_replace to take out <a href="users.php?id=3"> AND </a> Note - the id=3 could be any random number so i can't use exact strings to replace cos the value could be different. Thanks hope you can help. Quote Link to comment Share on other sites More sharing options...
joel24 Posted July 17, 2010 Share Posted July 17, 2010 $string = '<a href="users.php?id=3">Username</a>'; $string = strip_tags($string); will work, but it will remove all other HTML tags unless you add them as an exception. http://php.net/manual/en/function.strip-tags.php Quote Link to comment Share on other sites More sharing options...
EchoFool Posted July 17, 2010 Author Share Posted July 17, 2010 Yeh thats the thing i dont want it to strip all html Quote Link to comment Share on other sites More sharing options...
joel24 Posted July 17, 2010 Share Posted July 17, 2010 I'm sure you could do it easily with preg_replace or using strpos() and str_replace() and substr(). something like this would work, but i wouldn't rely on it. i'd go for preg_replace if someone experienced with regular expressions is kind enough to share their knowledge? $string = '<a href="users.php?id=3">Username</a>'; //get rid of closing </a> $string = str_replace("</a>", "", $string); //get position of end of anchor tag. add 2 to str pos because it returns start of "> $closePos = strpos($string, '">') + 2; $string = substr($string, $closePos, 100); Quote Link to comment Share on other sites More sharing options...
newbtophp Posted July 17, 2010 Share Posted July 17, 2010 $str = preg_replace('~<a[^>]+>(.+?)</a>~i', '$1', $str); Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.