PHP Check Each Time A Single String Contains A Substrain

85 Views Asked by At

I'd like to check each time a string contains a link and then extract it.

example:

'Check this out… https://www.link.co… and also check this out https://www.link2.co'

I know how to check if a string contains a substring ONCE using:

if (strpos($request_content, '!test') === 0) {}

however I dont know how to check each time and then extract that.. in this case i'd like to extract each link by finding the pattern http

so in the above example id like to output both links as variables like

var1 - https://www.link.co var2 - https://www.link2.co

How can I accomplish this? Thank you!

1

There are 1 best solutions below

2
JamalThaBoss On

The key in here is "pattern" as you said. In php, there is a function that has called "preg_replace" which basicly checks a pattern in your string and replaces it with something else you specified. So the code needs to be like this:

/*----- Define your string in here ------*/
    $my_text = 'Check this out… https://www.link.co… and also check this out https://www.link2.co';

/*----- Replace links in it ------*/
    $my_text = preg_replace('|([\w\d]*)\s?(https?://([\d\w\.-]+\.[\w\.]{2,6})[^\s\]\[\<\>]*/?)|i', '$1 <a href="$2">$3</a>', $my_text);

/*----- Echo result ------*/
    echo $my_text;