Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get http from string?

Tags:

regex

php

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)*
like image 371
Hamama Avatar asked Apr 21 '26 13:04

Hamama


2 Answers

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

like image 159
Murat Karagöz Avatar answered Apr 23 '26 06:04

Murat Karagöz


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;
like image 39
Pedro Lobito Avatar answered Apr 23 '26 08:04

Pedro Lobito