Reputation: 15270
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
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
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