0

I have a strings that contain URLs, and I want to be able to select the whole string. By which I mean break up into an array, and replace with a different URL. I am just struggling to get my head around how to get the full URL, which is done presumably for searching for strpos of http, and then the strpos of the next white space, the next white space, but I cant seem to get my head around how to achieve this.

$test = 'testing the test http://www.effef.com this is the end';
echo $pos = strpos($test,'http');

In this string, we would want to get the string 'http://www.effef.com'

How can you create a variable of a string which is a URL from a string?

2
  • 1
    possible duplicate of this Commented Feb 16, 2016 at 2:59
  • It would help if you posted some sample data Commented Feb 16, 2016 at 3:33

3 Answers 3

1

You do not need to break up that in an array and loop through it to replace it. You can just use preg_replace for your purpose.

$string = 'testing the test http://www.effef.com this is the end http://www.effef.com';

$replacement = 'http://www.newurl.com';
$regex = '/http:\/\/([^\s]+)/';

// if you are always sure that the url you want to replace is same then
// $regex = '/http\:\/\/www\.effef\.com/';

$new_string = preg_replace($regex, $replacement, $string);

var_dump($new_string);

Here is the working php-fiddle

However if you want to get that in an array for whatever reason, you can use preg_match_all

preg_match_all($regex, $string, $matches);
var_dump($matches);
Sign up to request clarification or add additional context in comments.

Comments

0

try this:

$test = 'testing the test http://www.effef.com this is the end http://www.facebook.com';
$arr = explode(" ", $test);
 foreach ($arr as $key => $value) {
     if (strpos($value, 'http') !== false) { echo $value."<br />"; }
 }

Comments

0

You could try

$string = "testing the test https://www.effef.com this is the end";

if (preg_match('/https?:\/\/[^\s"<>]+/', $string, $find_url)) {

$url = $find_url[0];

echo $url;

}

For me it echos out url http://www.effef.com/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.