问题
I am trying to replace "
on inch
i.e. 12" wall
would become 12 inch wall
I have 2 patterns working:
/\b([0-9]+)"/ -> preg_replace('/\b([0-9]+)"/', '$1 inch ', $string)
and
/\b([0-9]*)"/ -> preg_replace('/\b([0-9]*)"/', '$1 inch ', $string)
what is a difference between them then, why +
and *
works same way here ?
cheers, /Marcin
回答1:
The + means find the previous character/group 1 or more times.
The * means find the previous character/group any amount of times (0-infinity)
回答2:
/\b([0-9]+)"/
requires that there is at least one digit between the word boundary and the "
, whereas /\b([0-9]*)"/
also accepts zero digits. So the first does not match a space followed by "
and the second does.
If you want to mach both new 15 " tv
and new 15" tv
you need to match against a space character that may or may not be present:
/\b([0-9]+)\s?"/
This matches a word boundary, followed by a sequence (on or more) numbers, optionally followed by one space (or tab), followed by a "
. I presume that's what you are looking for.
If not, you should first define strings that must match and strings that may not match.
来源:https://stackoverflow.com/questions/6166996/regex-pattern-differences-and