Ryan
Ryan

Reputation: 15270

How can I trim whitespace from results of preg_match_all in PHP?

Given the function:

function getUrlsAndEmails($string) {
    $regex = '/(?:[^\s]+@[a-z]+(\.[a-z]+)+)|(?:(?:(?:[a-z]+:\/\/)|\s)[a-z]+(\.[a-z]+)+(\/[^\s]*)?)/';
    preg_match_all($regex, $string, $matches);
    return ($matches[0]);
}

Sometimes return results like:

Array
(
    [0] => google.com
    [1] =>  yahoo.com
)

How can I efficiently trim whitespace from all results of a preg_match_all()?

Of course I can loop through all of the results and trim(), but is there a more efficient way than adding this to the function above:

foreach ($matches[0] as $k => $v) {
    $matches[0][$k] = trim($v);
}

Upvotes: 1

Views: 874

Answers (2)

Danon
Danon

Reputation: 2973

Use map('trim').

<?php
$pattern = Pattern::of('(?:[^\s]+@[a-z]+(\.[a-z]+)+)|(?:(?:(?:[a-z]+:\/\/)|\s)[a-z]+(\.[a-z]+)+(\/[^\s]*)?)');
$matcher = $pattern->match($string);
   
var_dump($matcher->map('trim'));

result

Array
(
    [0] => 'google.com'
    [1] => 'yahoo.com'
)

Upvotes: 0

Razvan
Razvan

Reputation: 2596

Try this:

$regex = '/(?:[^\s]+@[a-z]+(\.[a-z]+)+)|(?:(?:(?:[a-z]+:\/\/)|(?!\s))[a-z]+(\.[a-z]+)+(\/[^\s]*)?)/';

It uses a negative lookahead assertion for the space.

Upvotes: 4

Related Questions