简体   繁体   English

正则表达式在前%后和后%前匹配

[英]Regular expression to match after first % and before last %

I need a regular expression that can match what is inside the "%" marks in the following string: 我需要一个正则表达式,可以匹配以下字符串中“%”标记内的内容:

1) Bla bla bla %yada yada yada% bla bla. 1)Bla bla bla%yada yada yada%bla bla。

Even if the form is like this: 即使表单是这样的:

2) Bla bla bla %yada yada yada% bla bla %yada #1 yada% 2)Bla bla bla%yada yada yada%bla bla%yada#1 yada%

I thought that /%([^%]*)%/ would do but in the second case it doesn't match the second part (%yada #1 yada%), only the first. 我以为/%([^%]*)%/可以,但是在第二种情况下,它与第二部分(%yada#1 yada%)不匹配,仅与第一部分匹配。

The expression has to match even if the substring between the "%" marks contains something like "#1". 即使“%”标记之间的子字符串包含类似“#1”的表达式,表达式也必须匹配。 Thank you in advance 先感谢您

Regards 问候

function replace($search, $replace, $subject, $link)
    {
        if (preg_match('/#[1-9]/', $search) == 1 && $link == null)
        {
            echo preg_replace($search, $replace, $subject);
        }
        if (preg_match('/%[a-zA-Z0-9# ]+%/', $search) == 1 && $link != null && $replace == null)
        {
            echo preg_replace('/%[a-zA-Z0-9# ]+%/', '<a href=$link>$1</a>', $subject, 1) . '<br>';
        }
    }

$string = 'bla bla #1 bla bla %bla bla% bla #2 %bla bla #3 bla%';
$newString = replace('/%[a-zA-Z0-9# ]+%/', null, $string, 'www.google.com');
echo $newString;
preg_match('/%[a-zA-Z0-9# ]+%/', $newString)); // 0 = no match

So on this second call I don't get a match. 所以在第二次通话中,我没有比赛。 Hope this helps. 希望这可以帮助。

See your calls to preg_match ... The second argument should be $subject not $search ... 查看您对preg_match的调用...第二个参数应为$subject而不是$search ...

Also, use return to actually return something, not echo . 另外,使用return实际返回某些内容,而不是echo

%.*%

This will match 这将匹配

1) a % 1)%

2) any number of any characters 2)任何数量的任何字符

3) a % 3)%

And since it will match greedily rather than lazily, it will match the widest %...% it can, rather than stop at the first. 而且由于它会贪婪地匹配而不是懒惰地匹配,因此它将匹配它可以匹配的最大%...%,而不是首先停止。

For example, the lazy version of this would be %.*?% (putting ? after a * makes it lazy) and it would close after the first, not last %. 例如,它的惰性版本将是%。*?%(在*后面加上?使其变为惰性),并且它将在第一个而不是最后一个%之后关闭。

/%.+?%/ should do the trick. /%.+?%/应该可以解决问题。
See greedyness of regex expressions. 请参阅正则表达式的贪婪性。
[^%] stops at the first % . [^%]在第一个%处停止。 But you want to include all characters between the two % s. 但是,您希望在两个% s之间包含所有字符。

Try this expression 试试这个表情

%[a-zA-Z0-9# ]*%

Hope it helps 希望能帮助到你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM