0

Here is the code I found in stackoverflow, but it has an issue, someone help me to get it fixed.

<?php
$string = "Apple iPhone SE (Black, 64 GB)
http://dl.flipkart.com/dl/apple-iphone-se-black-64-gb/p/itm832dd5963a08d?pid=MOBFRFXHCKWDAC4A&cmpid=product.share.pp";

foreach(explode(" ",$string) as $first_occurrence) {
  if (strpos($first_occurrence, 'http') !== false) { break;}
}

echo $first_occurrence;
?>

The result is

GB) http://dl.flipkart.com/dl/apple-iphone-se-black-64-gb/p/itm832dd5963a08d?pid=MOBFRFXHCKWDAC4A&cmpid=product.share.pp

There is an unwanted GB) There is a line break after "...64 GB)", if I remove that, the code seems to be working correctly. But I also want to make it work with line breaks.

How can I get accurate output as following?

http://dl.flipkart.com/dl/apple-iphone-se-black-64-gb/p/itm832dd5963a08d?pid=MOBFRFXHCKWDAC4A&cmpid=product.share.pp

Here is another more complicated string,

$string = "Samsung Galaxy S20 (Black) https://www.amazon.in/b?node=21021782031&pf_rd_r=Z8266H8XJMQGEZMB0X44&pf_rd_p=00f7186e-02c5-40c7-9f15-9f2d65d70297 afdsfdsf d https://stackoverflow.com/questions/35433139/php-get-only-values-from-an-array and  https://mail.google.com/mail/u/0/#inbox";

The result should be

https://www.amazon.in/b?node=21021782031&pf_rd_r=Z8266H8XJMQGEZMB0X44&pf_rd_p=00f7186e-02c5-40c7-9f15-9f2d65d70297
Malavika P
  • 23
  • 5

2 Answers2

2

This is probably more easily achieved using regex. preg_match will return the first match inside the string:

$string = "Apple iPhone SE (Black, 64 GB)
http://dl.flipkart.com/dl/apple-iphone-se-black-64-gb/p/itm832dd5963a08d?pid=MOBFRFXHCKWDAC4A&cmpid=product.share.pp";

preg_match('~https?://[^\s]*~', $string, $matches);
echo $matches[0];

Output:

http://dl.flipkart.com/dl/apple-iphone-se-black-64-gb/p/itm832dd5963a08d?pid=MOBFRFXHCKWDAC4A&cmpid=product.share.pp

Demo on 3v4l.org

Nick
  • 138,499
  • 22
  • 57
  • 95
0

You can do it this way too:

$string = "Apple iPhone SE (Black, 64 GB)
http://dl.flipkart.com/dl/apple-iphone-se-black-64-gb/p/itm832dd5963a08d?pid=MOBFRFXHCKWDAC4A&cmpid=product.share.pp";

foreach(explode("http",$string) as $first_occurrence) {
  if (strpos($first_occurrence, '://') !== false) { break;}
}

echo $first_occurrence;

Hope it helps.

Serghei Leonenco
  • 3,478
  • 2
  • 8
  • 16