Page 1 of 1

exploding a sting multiple times

Posted: Mon Nov 23, 2009 3:55 am
by mupparion
Hi,

I have a string which will contain an unknown amount of URLs in it in html format and i need to explode this string and get all the URLs from it.

Code: Select all

 
<?php
 
$string = "bla bla bleh <a href='http://www.link.com'>link name</a> blek bla bla <a href='http://www.linkage.com'>link name</a> blek bla bla";
 
for($i=0;$i<2;$i++){
 
$exp = explode("<a href='", $string);
 
$exp2 = explode("'>", $exp[1]);
 
echo $exp2[0];
echo "<br />";
 
}
?>
 
Above is what i currently have. So as you can see in this example there are two link tags which contain a URL and i need to be able to display the URLs that are in that tag.

The above works to an extent in the sense that it lists two links but its listing http://www.link.com twice instead of http://www.link.com and http://www.linkage.com

Any ideas?

Cheers!

Re: exploding a sting multiple times

Posted: Mon Nov 23, 2009 4:23 am
by John Cartwright
Regex is definitely the way to go here. No need for messy parsing. If all your <a> tags are in a uniform format, a simple regex would suffice.

Code: Select all

preg_match_all("~<a href='(.*?)'>(.*?)</a>~i", $yourhtml, $matches);
 
echo '<pre>';
print_r($matches);
Otherwise, you'll have to upgrade the expression to be more flexible.

Re: exploding a sting multiple times

Posted: Mon Nov 23, 2009 5:58 am
by mupparion
works perfect :D

thank you!

Re: exploding a sting multiple times

Posted: Tue Nov 24, 2009 4:46 am
by mupparion
Just another Q about this.

It works fine when does that example. But when i change
$yourhtml = "bla bla bleh <a href='http://www.link.com'>link name</a> blek bla bla <a href='http://www.linkage.com'>link name</a> blek bla bla";

to

$yourhtml = $_POST['text'];

It doesnt seem to work?
When i submit a form it should search the textarea field called text and then show the links in that but it comes up with nothing.

Is there something different you have to do when getting the data from POST as oppose to a variable string?

Below is what i have:

Code: Select all

 
<?php
if($_POST['update']){
$textit = $_POST['text'];
$string = "bla bla bleh <a href='http://www.link.com'>link name</a> blek bla bla <a href='http://www.linkage.com'>link name</a> blek bla bla";
 
preg_match_all("~<a href='(.*?)'>(.*?)</a>~i", $textit, $matches);
echo '<pre>';
print_r($matches);
echo '</pre>';
?>
 
So when changing it to search $string it works but not for $textit

Cheers!

Re: exploding a sting multiple times

Posted: Tue Nov 24, 2009 9:54 am
by mupparion
anyone have any ideas :banghead: :banghead:

Re: exploding a sting multiple times

Posted: Wed Nov 25, 2009 4:51 am
by mupparion
Just for the purpose of Google searches

I solved this after a bit of thought.

Instead of searching the text straight from the $_POST['test'] i first submitted it to my MySQL database and then searched from within the database and it worked perfect!