user2854563
user2854563

Reputation: 268

Regex to find the text between certain code

my text is like this;

[name]JAAN JOHN[/name]
[cell]09178656469[/cell]
[city]Dhaka[/city]

I want to get text in between each of the above [ ] quotes using regex. Please pardon me since I searched alot this site but unable to get my required answer. Please help!

EDITED:

For example, I want to get the result like this:

Name: JAAN JOHN
Cell #: 09178656469
City: Dhaka

How to get this result?

Upvotes: 0

Views: 53

Answers (3)

Braj
Braj

Reputation: 46841

Use back reference and get the matched group from index 2. In below sample code I am interested in cell tag

\[(cell)\](.*?)\[\/\1\]

Here is demo


If you are interested in all tags of matching end tag then try

\[(.*?)\](.*?)\[\/\1\]

Here is demo

Get the desired tag name from index 1 and value from index 2.

sample code:

$re = "/\\[(.*?)\\](.*?)\\[\\/\\1\\]/";
$str = "[name]JAAN JOHN[/name]\n[cell]09178656469[/cell]\n[city]Dhaka[/city]";

preg_match_all($re, $str, $matches);

Upvotes: 2

Ghilas BELHADJ
Ghilas BELHADJ

Reputation: 14096

Use Lookahead and Lookbehind Assertions

((?<=]).*(?=\[\/))

See this demo

Upvotes: 1

Tim Zimmermann
Tim Zimmermann

Reputation: 6420

This regex will do for each line.

\[[^\]]+\](.*?)\[\/[^\]]+\]

Test the regex here.

Upvotes: 1

Related Questions