josandi - YM
josandi - YM

Reputation: 43

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

Upvotes: 1

Views: 111

Answers (4)

hwnd
hwnd

Reputation: 70722

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

Upvotes: 4

bachN
bachN

Reputation: 612

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"

Upvotes: 0

skamazin
skamazin

Reputation: 757

You could try this one:

--#(.*)#--

DEMO

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174696

Through sed,

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

Section 3

Section 4

Section 5

Upvotes: 0

Related Questions