【问题标题】:get the words between two specific characters in php获取php中两个特定字符之间的单词
【发布时间】:2014-09-23 15:30:23
【问题描述】:

如何获取字符“--#”和“#--”之间的单词 我尝试了正则表达式并爆炸,但我无法获得所需的输出。

输出必须是: Section 2, Section 3, Section 4, Section 5 ..................................................... ....................

--#第2节#-- -##Lorem ipsum dolor sit amet,consectetur adipisicing elit,sed do eiusmod tempor incididunt##-

--#第3节#-- -##Lorem ipsum dolor sit amet,consectetur adipisicing elit,sed do eiusmod tempor incididunt##-

--#第4节#-- -##Lorem ipsum dolor sit amet,consectetur adipisicing elit,sed do eiusmod tempor incididunt##-

--#第5节#-- -##Lorem ipsum dolor sit amet,consectetur adipisicing elit,sed do eiusmod tempor incididunt##-

【问题讨论】:

  • @fedorqui:或者没有 - 很可能
  • /#(.*?)#/,也许?
  • 它实际上只有 php 和正则表达式。我只是点击了建议。对此感到抱歉。顺便感谢那些帮助我的人。

标签: php regex


【解决方案1】:

通过 sed,

$ sed 's/.*--#\(.*\)#--.*/\1/g' file
Section 2

Section 3

Section 4

Section 5

【讨论】:

    【解决方案2】:

    你可以试试这个:

    --#(.*)#--
    

    DEMO

    【讨论】:

      【解决方案3】:

      由于问题的标题明确指出:

      获取php....中两个特定字符之间的单词。

      你可以使用这个正则表达式:

      preg_match_all('/--#(.*?)#--/', $text, $matches);
      print_r($matches[1]);
      

      解释

      --#      # match '--#'
      (        # group and capture to \1:
        .*?    #   any character except \n (0 or more times)
      )        # end of \1
      #--      # match '#--'
      

      Working Demo

      【讨论】:

      • 这正是我需要的。,非常感谢,希望它也能对某些人有所帮助。,
      【解决方案4】:

      如果你使用 BASH

      不使用 sed 或任何其他命令的简单答案是执行以下操作

       VAR="--#Section 2#-- -##Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt##-"
      
       #delete from the tail 
       VAR=${VAR%%'#--'*}                             //you will get VAR="--#Section 2"
       #delete from the head
       VAR=${VAR##*'--#'}                             //NOW you'll have VAR="Section 2"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-06-16
        • 2012-10-22
        • 1970-01-01
        • 1970-01-01
        • 2016-12-06
        • 1970-01-01
        • 1970-01-01
        • 2019-05-12
        相关资源
        最近更新 更多