当前位置: 动力学知识库 > 问答 > 编程问答 >

regex - get the words between two specific characters in php

问题描述:

How to get the words between the characters "--#" and "#--"

I tried regex and explode but I cant get the desired output.

output must be : Section 2, Section 3, Section 4, Section 5

.................................................................................

--#Section 2#--

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

--#Section 3#--

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

--#Section 4#--

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

--#Section 5#--

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

网友答案:

Since the title of the question clearly states:

get the words between two specific characters in php....

You can use this regex:

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

Explanation:

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

Working Demo

网友答案:

Through sed,

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

Section 3

Section 4

Section 5
网友答案:

You could try this one:

--#(.*)#--

DEMO

网友答案:

If you use BASH

a simple answer without using sed or any other command is by doing the following

 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"
分享给朋友:
您可能感兴趣的文章:
随机阅读: