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 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?