du997562
2014-02-25 21:54
浏览 222
已采纳

如何从PHP中的preg_match_all结果中修剪空格?

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);
}

图片转代码服务由CSDN问答提供 功能建议

给定函数:

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

有时返回结果如:

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

如何有效地修剪空白 来自 preg_match_all()的所有结果?

当然我可以循环遍历所有结果和 trim(),但是 有没有比将其添加到上述函数更有效的方法:

  foreach($ matches [0] as $ k => $ v){
 $ matches [  0] [$ k] = trim($ v); 
} 
   
 
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doubang4881 2014-02-25 22:07
    已采纳

    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.

    点赞 打赏 评论

相关推荐 更多相似问题