douhe1864 2009-02-18 00:34
浏览 138
已采纳

匹配正则表达式中的空格

I need to match a space character in a PHP regular expression. Anyone got any ideas?

I mean like "gavin schulz", the space in between the two words. I am using a regular expression to make sure that I only allow letters, number and a space. But I'm not sure how to find the space. This is what I have right now:

$newtag = preg_replace("/[^a-zA-Z0-9s|]/", "", $tag);
  • 写回答

9条回答 默认 最新

  • drmticpet66231422 2009-02-18 00:51
    关注

    If you're looking for a space, that would be " " (one space).

    If you're looking for one or more, it's " *" (that's two spaces and an asterisk) or " +" (one space and a plus).

    If you're looking for common spacing, use "[ X]" or "[ X][ X]*" or "[ X]+" where X is the physical tab character (and each is preceded by a single space in all those examples).

    These will work in every* regex engine I've ever seen (some of which don't even have the one-or-more "+" character, ugh).

    If you know you'll be using one of the more modern regex engines, "\s" and its variations are the way to go. In addition, I believe word boundaries match start and end of lines as well, important when you're looking for words that may appear without preceding or following spaces.

    For PHP specifically, this page may help.

    From your edit, it appears you want to remove all non valid characters The start of this is (note the space inside the regex):

    $newtag = preg_replace ("/[^a-zA-Z0-9 ]/", "", $tag);
    #                                    ^ space here
    

    If you also want trickery to ensure there's only one space between each word and none at the start or end, that's a little more complicated (and probably another question) but the basic idea would be:

    $newtag = preg_replace ("/ +/", " ", $tag); # convert all multispaces to space
    $newtag = preg_replace ("/^ /", "", $tag);  # remove space from start
    $newtag = preg_replace ("/ $/", "", $tag);  # and end
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(8条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题