查找带有美元符号的单词
find word with dollar sign
我试图使用正则表达式查找第一个字符为 ($) 的单词,但无法正常工作。
我试过了:
$string = '$David is the cool, but $John is not cool.';
preg_match('/\b($\w+)\b/', $string, $matches);
我试图转义 $ 但仍然无效:
preg_match('/\b($\w+)\b/', $string, $matches);
我想提取 [$David, $John] .
请帮忙!
\b
不会匹配非单词字符和 $
(另一个非单词字符)。
\b
等同于
(?<!\w)(?=\w)|(?<=\w)(?!\w)
所以你可以使用
/(?<!\w)($\w+)\b/
也就是说,可能没有理由检查 $
之前的内容,因此应该执行以下操作:
/($\w+)\b/
此外,\b
将始终匹配,因此可以将其省略。
/($\w+)/
此外,您似乎想要所有匹配项。为此,您需要使用 preg_match_all
而不是 preg_match
.
如前所述,不需要使用单词边界和非单词边界,但是要匹配其他变量,您必须使用 preg_match_all:
$string = '$David is the cool, but $John is not cool.';
preg_match_all('/($\w+)/', $string, $matches);
print_r($matches);
输出:
Array
(
[0] => Array
(
[0] => $David
[1] => $John
)
[1] => Array
(
[0] => $David
[1] => $John
)
)
我试图使用正则表达式查找第一个字符为 ($) 的单词,但无法正常工作。 我试过了:
$string = '$David is the cool, but $John is not cool.';
preg_match('/\b($\w+)\b/', $string, $matches);
我试图转义 $ 但仍然无效:
preg_match('/\b($\w+)\b/', $string, $matches);
我想提取 [$David, $John] .
请帮忙!
\b
不会匹配非单词字符和 $
(另一个非单词字符)。
\b
等同于
(?<!\w)(?=\w)|(?<=\w)(?!\w)
所以你可以使用
/(?<!\w)($\w+)\b/
也就是说,可能没有理由检查 $
之前的内容,因此应该执行以下操作:
/($\w+)\b/
此外,\b
将始终匹配,因此可以将其省略。
/($\w+)/
此外,您似乎想要所有匹配项。为此,您需要使用 preg_match_all
而不是 preg_match
.
如前所述,不需要使用单词边界和非单词边界,但是要匹配其他变量,您必须使用 preg_match_all:
$string = '$David is the cool, but $John is not cool.';
preg_match_all('/($\w+)/', $string, $matches);
print_r($matches);
输出:
Array
(
[0] => Array
(
[0] => $David
[1] => $John
)
[1] => Array
(
[0] => $David
[1] => $John
)
)