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)*
Hamama
  • 177
  • 4
  • 16

4 Answers4

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

Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107
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
Hikmat Sijapati
  • 6,869
  • 1
  • 9
  • 19
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

Vishnu Bhadoriya
  • 1,655
  • 1
  • 20
  • 28
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;
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268