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

如何从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);
}
  • 写回答

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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 在使用pyecharts时出现问题
  • ¥15 深度学习残差模块模型
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计