[英]regex - return part of string when it finds the second occurrence of a character say "$" in php
Here i am having a string "one two $\\alpha \\beta $ three"
.在这里,我有一个字符串"one two $\\alpha \\beta $ three"
。
What i need is to get the part of string until its second occurrence of a character here it is "$"
or may be group of characters "$$"
.我需要的是获取字符串的一部分,直到它第二次出现这里的字符为止,它是"$"
或者可能是字符组"$$"
。
ie, output should be "one two $\\alpha \\beta $"
and "one two $$\\alpha \\beta $$"
if the string is "one two $$\\alpha \\beta $$ three"
.即,如果字符串是"one two $$\\alpha \\beta $$ three"
,则输出应该是"one two $\\alpha \\beta $"
和"one two $$\\alpha \\beta $$"
"one two $$\\alpha \\beta $$ three"
。
Using the regex /.*\\$.*\\$/
will give you what you want.使用正则表达式/.*\\$.*\\$/
会给你你想要的。
This code这段代码
$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>";
will give the following output将给出以下输出
one two $\alpha \beta $
one two $$\alpha \beta $$
So I guess that's what you want.所以我想这就是你想要的。 Or...?或者...?
Regards问候
Solution with preg_match
function:使用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 $"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.