regex - get the words between two specific characters in php

236

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##-

770

Answer

Solution:

Since the title of the question clearly states:

get the words between two specific characters inphp....

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

709

Answer

Solution:

Through sed,

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

Section 3

Section 4

Section 5
796

Answer

Solution:

You could try this one:

--#(.*)#

DEMO

631

Answer

--

Solution:

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"

People are also looking for solutions to the problem: javascript - Remove Quotes from json_encoded string value

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.