douxi5940 2013-12-29 16:13
浏览 30
已采纳

使用正则表达式从文本中获取多个字符串[关闭]

I have the following set of strings in a PHP file.

echo '<div class="alert"><b>',__('ERROR!'),'</b> ',__('Please fix following errors!'),'</div>';
echo sprintf(__('hello %s'), $name);
___('Hello');

__() function returns string and ___() function echo's a string. I have written a regex to grab text in between __('') or ___('') but it's not working properly.

Here is my regex

if(preg_match_all("#(__{2,3}(\((.*)\),|;))#",$text, $matches))

and output I get is:

__('ERROR!'),' ',__('Please fix following errors!'), (Incorrect result)
__('hello %s'),

For the ___() function I am using quantifier _{2,3} but it's not picking up this function. How do I get the string only from the functions?

  • 写回答

2条回答 默认 最新

  • doudaifu6083 2013-12-29 16:19
    关注

    You are using __{2,3}. a{n,m} repeats the previous item between n and m times. So __{2,3} matches an underscore followed by 2 or 3 underscores. You're trying to match an underscore repeated 2 or 3 times, so use _{2,3} instead.

    Then, you're using ,|; to match a comma or a semicolon. This does not work as you expect. | is used to specify alternatives. For example, (foo|bar) matches either foo or bar. In your regex, you're using (\((.*)\),|;), and this will mean match \((.*)\), or ; -- which is not what you want. To match a , or ;, use a character class -- [,;].

    (.*) is greedy and will match as many characters as possible. If you use the regex a.*c on a stringabcabc, it will match the whole string abcabc. But a.*?c will only match the first abc. By adding the ? after the *, we tell it to repeat as few times as possible.

    The correct regular expression would be:

    preg_match_all('#_{2,3}\([\'"](.*?)[\'"]\)[,;]#', $text, $matches);
    

    Regex101 demo.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?