3

I have the following string:

"http://add.co" id="num_1"

How can I get only "http://add.co" from this string?

I tried to use pattern:

^http:\/\/(+s)*
3
  • Try explode(" ", $str)[0]. Or can there be strings with no URL at the start? Then try '~^"?https?://\S+)*~' Commented Jan 18, 2017 at 13:38
  • stackoverflow.com/questions/6768793/get-the-full-url-in-php this will help you out. Commented Jan 18, 2017 at 13:45
  • I confused with your question.what you want http or http://add,co.. See answer. Commented Jan 18, 2017 at 14:21

4 Answers 4

2

You could use this regex ^"http:\/\/[^"]+(?=") which almost captures your url.

String : "http://add.co" id="num_1"
Matches : "http://add.co

You could append a last " to the match to fix it. Maybe someone can edit my regex to include the last ".

See example here: https://regex101.com/r/oppeaQ/1

Sign up to request clarification or add additional context in comments.

Comments

1

There are a couple of ways to achieve what you want:

With preg_match:

$str = '"http://add.co" id="num_1"';
preg_match('/^"(.*?)"/', $str, $matches);
echo $matches[1];

With str_replace and explode:

$str = '"http://add.co" id="num_1"';
$url = str_replace("\"", "", explode(" ", $str)[0]);
echo $url;

Comments

1
<?php
$string = '"http://add.co id="num_1"';
preg_match_all('/[a-z]+:\/\/\S+/', $string, $matches);
print($matches[0][0]);
?>

o/p

http://add.co //tested in my machine

Comments

1

Like this:

1)The explode() function breaks your string into array based on seperator.

2).The preg_replace() replaces the contains of string matched with defined regular expression.

$string = '"http://add.co" id="num_1"';
$array = explode(':',$string);
echo preg_replace('/\"/','',$array[0]);

Output:

http

AND

$string = '"http://add.co" id="num_1"';
$array = explode(' ',$string);
echo preg_replace('/\"/','',$array[0]);

Output:

http://add.co

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.