Search Marketing


Finding Anchor Tags in a Text String

Mon Oct 26, 2009 12:23 pm
Comments: 0 Views: 130

If you need to go through a block of text and locate, modify or replace html links to add no-follow, target options, titles, or alt text then there is a pretty easy way to do it with php using regular expressions and the php explode function.

The following code can help a beginning programmer understand how you breakdown a string to get at what you need.

Lets assume the following is in a function and you feed this part of your program a block of user-generated text:

$str = stripslashes($str);
$preg = "/<[s]*a[s]*href=[s]*["']?([w.-]*)["']?[^>]*>(.*?)/i";

// the preg variable matches html charactersyou are looking for

if(preg_match_all($preg, $str, $match))

// the preg_match_all() function takes the $preg code and uses it to find every instance of the match

foreach ($match[1] as $key=>$val)

// foreach just loops through all the instances


$txt = $match[0][$key];
$link = explode(""",$txt);
$linktext = $match[2][$key];

// in this situation we used the explode() function to break up the anchor tag at the double quotes to find the href url

$pattern[] = '/'.preg_quote($match[0][$key],'/').'/';
$replace[] = "<a href="$link[1]" rel="nofollow" target="_blank">$linktext</a>";

// in this example we wanted to change any matches to be a no-follow link and put the string back together to feed the string back into the program


preg_replace($pattern, $replace, $str);

// one thing to make note of is that in this example if no link matches are found it will not return anything to your program

// you should add that if anything is not matched just return the original string back to your program


URL: http: (ex.
Math (13 + 2)
* required

© 2019 Christonium LLC
Terms of Use