views:

48

answers:

2

Hello everyone, how can i extract the http from this text?

"Text: Here's 2 free bonuses. http://blablabla.blabla/blabla "

But the url can also be another one.

Finaly After i have the array, wich contains usualy just one url, how can i add it to the above text exactly at the same position? but with html tag <a> the results should look something like this

"Text: Here's 2 free bonuses. 
<a href='http://blablabla.blabla/blabla'&gt;http://blablabla.blabla/blabla&lt;/a&gt; "
+1  A: 

This regex should do the trick:

$s= "Text: Here's 2 free bonuses. http://blablabla.blabla/blabla and some more text";
$s2= preg_replace('~(http://\S+)\b~', '<a href="$1">$1</a>', $s);
var_dump($s2);
pygorex1
how can i use this for an array ?
streetparade
According to the docs the third parameter can be an array of strings to apply the regex to: http://us3.php.net/preg_replace
pygorex1
+1  A: 

You can do that using regular expression, and more precisely preg_replace(). The matching expression can be something like :

$pattern = 'http://[a-zA-Z0-9\.\-/]+';

Of course, you can refine it for more precise matching, but this should do the trick. If you want to play with regex, have a look at regexpal, it's a great tool for testing. Then, you can perform the replace ($0 corresponds to the whole matched string :

preg_replace($pattern, '<a href="$0">$0</a>', $yourString);
Wookai
how can i used for an array without going throw a foor loop?
streetparade
According to the doc (see the link in my answer), `preg_replace()` works with $yourString being an array of strings (returns an array).
Wookai