Jump to content

Regex search function


Wolphie

Recommended Posts

Ok, so i'm trying to search google for specific keywords. However, clearly it's not working like i'd like it to, I'm not too sure what i've done wrong.

But, I want to return an anchor's href, and the name.

 

I.e.

 

<a href="[i want this]http://www.phpfreaks.com[/i want this]">[i want this]PHPFreaks[/i want this]</a>

 

This is what i have:

 

<?php
function search($str) {
	$reg = '~(<h2 class=r><a href="(.*?[^"])" class=l>(.*?)</a>.*?</h2>)~si';
	$val = 'http://www.google.com/search?hl=en&q=' . $str . '&btnG=Google+Search';
                $val = str_replace(' ', '+', $val);

	if(preg_match_all($reg, file_get_contents($val), $links))
		return array('anchor' => $links[3], 'href' => $links[2]);
}
?>

 

I want to be able to loop through them e.g.

 

<?php
$search = search($str);
foreach($search['href'] as $href) {
  echo '<a href="' . $href . '">' . $search['anchor'] . '</a>';
}
?>

 

Is this possible, and is there a better way? If so, could somebody provide an example please?

Link to comment
https://forums.phpfreaks.com/topic/104011-regex-search-function/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.