在这里我有一个字符串"one two $'alpha 'beta $ three"
.
我需要的是获取字符串的一部分,直到它第二次出现这里的字符"$"
或者可能是一组字符"$$"
。
即,输出应该是 "one two $'alpha 'beta $"
和 "one two $$'alpha 'beta $$"
字符串是否"one two $$'alpha 'beta $$ three"
。
使用正则表达式/.*'$.*'$/
会给你你想要的。
此代码
$ptrn='/.*'$.*'$/';
preg_match_all($ptrn, "one two $'alpha 'beta $ three", $matches);
echo $matches[0][0] . "<br>";
preg_match_all($ptrn, "one two $$'alpha 'beta $$ three", $matches);
echo $matches[0][0] . "<br>";
将给出以下输出
one two $'alpha 'beta $
one two $$'alpha 'beta $$
所以我想这就是你想要的。或者...?
问候
具有preg_match
函数的解决方案:
$str = "one two $'alpha 'beta $ three one two $$'alpha 'beta $$ three";
preg_match("/[^$]+?[$]{1,2}[^$]+?[$]{1,2}/i", $str, $matches);
// [^$] - matches all symbols excepting '$'
// [$]{1,2} - symbolic class - matches only '$' symbol in quantity from 1 to 2
// ? - supply "ungreedy" matching
var_dump($matches);
// the output: "one two $'alpha 'beta $"