Question

Given the following code:

$regex = '/(http\:\/\/|https\:\/\/)([a-z0-9-\.\/\?\=\+_]*)/i';
$text = preg_split($regex, $note, -1, PREG_SPLIT_DELIM_CAPTURE);

its returning an array such as:

array (size=4)
  0 => string '...' (length=X)
  1 => string 'https://' (length=8)
  2 => string 'duckduckgo.com/?q=how+much+wood+could+a+wood-chuck+chuck+if+a+wood-chuck+could+chuck+wood' (length=89)
  3 => string '...' (length=X)

I would prefer it if the returned array had size=3, with one single URL. Is this possible?

Was it helpful?

Solution

Sure that can be done, just remove those extra matching groups from your regex. Try following code:

$regex = '#(https?://[a-z0-9.?=+_-]*)#i';
$text = preg_split($regex, $note, -1, PREG_SPLIT_DELIM_CAPTURE);

Now resulting array will have 3 elements in the array instead of 4.

Besides removing extra grouping I have also simplified your regex also since most of the special characters don't need to be escaped inside character class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top