douzou8074 2013-01-22 08:45
浏览 58
已采纳

用正则表达式替换字符串

I'm trying to extract from a string like this:

$message = #porrabarça per avui @RTorq el  @FCBar guanyarà per 3-1 al AC Milan

The '3-1'. As Number - Number

I've tried

$message = preg_replace('/[0-9]\s*-\s[0-9]/i', '', $message);

But it isnt working. It's output is the same as the input.

Can you help me out?

  • 写回答

2条回答 默认 最新

  • douyuan5600 2013-01-22 08:47
    关注

    The problem is \s here.

    /[0-9]\s*-\s[0-9]/
               ^
               |
               +--- This makes a single space mandatory. 
    

    You need \s* there. Use preg_match to extract anything. preg_match matches and optionally set the match to a variable. From there you can extract the matches. preg_replace replaces the matched content.

    preg_match("/\d+\s*-\s*\d+/", $message, $match);
    $num = $match[0];
    

    http://ideone.com/BWKZQV

    To replace use this pattern and empty string as replace string in preg_replace.

    A better pattern would using POSIX character classes. it'll match any type digit characters of any other locale.

    /[[:digit:]]+[[:space:]]*-[[:space:]]*[[:digit:]]+/
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊