Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
454 views
in Technique[技术] by (71.8m points)

php - 匹配正则表达式中的空格(Matching a space in regex)

I need to match a space character in a PHP regular expression.

(我需要匹配PHP正则表达式中的空格字符。)

Anyone got any ideas?

(有人有任何想法吗?)

I mean like "gavin schulz", the space in between the two words.

(我的意思是“gavin schulz”,这两个词之间的空间。)

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);
  ask by Gavin Schulz translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).

(如果您正在寻找公共间距,请使用"[ X]""[ X][ X]*""[ X]+" ,其中X是物理制表符(并且每个字符前面都有一个空格)那些例子)。)

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.

(如果你知道你将使用一个更现代的正则表达式引擎, "\s"及其变化是要走的路。)

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.

(特别是对于PHP, 这个页面可能会有帮助。)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...