duanlao1552 2017-03-28 09:06
浏览 51
已采纳

带有特殊字符的正则表达式

I have this code from which I like to return an array that holds all hits for patterns that starts with 'some' and ends with 'string'.

$mystr = "this string contains some variables such as  $this->lang->line('some_string') and $this->lang->line('some_other_string')";
preg_match_all ("/\bsome[\w%+\/-]+?string\b/", $mystr, $result);

However I like to have all hits that starts with

$this->lang->line('

and ends with

')

Furthermore, I need to have the start and end patterns left out. In other words, I like to see 'some_string' and 'some_other_string' in my resulting array. Replacing 'some' and 'string' straight forward is not working, because of special characters?

  • 写回答

2条回答 默认 最新

  • doudi2005 2017-03-28 09:30
    关注

    Here an example that escapes the special chars for you:

    $mystr = "this string contains some variables such as \$this->lang->line('some_string') and \$this->lang->line('some_other_string')";
    #array of regEx special chars
    $regexSpecials = explode(' ',". ^ $ * + - ? ( ) [ ] { } \\ |");
    
    #test string 1
    #here we have the problem that we have $ and ', so if we use
    # single-quotes we have to handle the single-quote in the string right.
    # double-quotes we have to handle the dollar-sign in the string right.
    $some = "\$this->lang->line('";
    
    #test string 2
    $string = "')";
    
    #escape   chr(92) means \ 
    foreach($regexSpecials as $chr){
       $some = str_replace($chr,chr(92).ltrim($chr,chr(92)),$some);
       $string = str_replace($chr,chr(92).ltrim($chr,chr(92)),$string);
    }
    
    #match 
    preg_match_all ('/'.$some.'(.*?)'.$string.'/', $mystr, $result);
    
    #show
    print_r($result);
    

    The hard part is to escape everthing right in php and in the regexstring.

    • You have to escape the dollar sign in php right when used in double-quotes
    • Also you have escape all special characters right for the regex.

    Read more here:

    What special characters must be escaped in regular expressions?

    What does it mean to escape a string?

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

报告相同问题?

悬赏问题

  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂