可选的空白正则表达式 [英] Optional Whitespace Regex
问题描述
我在尝试忽略某些字符之间的空格时遇到问题.我已经搜寻了几天,似乎找不到正确的解决方案.
I'm having a problem trying to ignore whitespace in-between certain characters. I've been Googling around for a few days and can't seem to find the right solution.
这是我的代码:
// Get Image data
preg_match('#<a href="(.*?)" title="(.*?)"><img alt="(.*?)" src="(.*?)"[\s*]width="150"[\s*]height="(.*?)"></a>#', $data, $imagematch);
$image = $imagematch[4];
基本上,这是我遇到的一些情况:
Basically these are some of the scenarios I have:
<a href="/wiki/File:Sky1.png" title="File:Sky1.png"><img alt="Sky1.png" src="http://media-mcw.cursecdn.com/thumb/5/56/Sky1.png/150px-Sky1.png"width="150" height="84"></a>
(请注意,width ="和src ="之间没有空格)
(Notice the lack of a space between width="" and src="")
还有
<a href="/wiki/File:TallGrass.gif" title="File:TallGrass.gif"><img alt="TallGrass.gif" src="http://media-mcw.cursecdn.com/3/34/TallGrass.gif" width="150"height="150"></a>
(请注意,在width ="和height ="之间没有空格.)
(Notice the lack of a space in between width="" and height="".)
是否有任何地方可以忽略这些字符之间的空格?因为我不是Regex专家.
Is there anyway to ignore the whitespace in between those characters? As I am not a Regex expert.
推荐答案
如果可以允许空格,请添加\s?
.
Add a \s?
if a space can be allowed.
\ s 代表空白
?说前面的字符可能出现一次或不发生.
? says the preceding character may occur once or not occur.
如果允许多个空格并且是可选空格,请使用\s*
.
If more than one spaces are allowed and is optional, use \s*
.
* 说前面的字符可以出现零次或多次.
* says preceding character can occur zero or more times.
'#<a href\s?="(.*?)" title\s?="(.*?)"><img alt\s?="(.*?)" src\s?="(.*?)"[\s*]width\s?="150"[\s*]height\s?="(.*?)"></a>#'
在属性名称和=之间留有一个可选空格.
allows an optional space between attribute name and =.
如果您还希望在=
后面添加一个可选空格,请在其后也添加一个\s?
.
If you want an optional space after the =
also, add a \s?
after it also.
同样,无论您在何处有可选字符,如果最大出现次数是 1 ,则可以使用?
;如果最大出现次数是无限的,则可以使用*
(在可选字符之后).
Likewise, wherever you have optional characters, you can use ?
if the maximum occurrence is 1 or *
if the maximum occurrence is unlimited, following the optional character.
您的实际问题是[\s*]
,由于[
和]
中包含的字符是字符类,导致出现空白或 a * .字符类允许一次其任何成员出现(因此从中删除*
),并且如果在]
任何字符之后附加了量词(?
,+
,*
等)字符类中的字符可以根据量词出现.
And your actual problem was [\s*]
which causes occurrence of a whitespace or a * as characters enclosed in [
and ]
is a character class. A character class allows occurrence of any of its members once (so remove *
from it) and if you append a quantifier (?
, +
, *
etc) after the ]
any character(s) in the character class can occur according to the quantifier.
这篇关于可选的空白正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!