0

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?

5
  • Did you try anything? Commented Aug 16, 2014 at 10:34
  • I'm really sorry sir! but I'm very new to regex. I can write code with PHP but its hard for me to write regex. Please help Commented Aug 16, 2014 at 10:35
  • You say "between each of the above [ ]". I suspect you don't mean that; you mean between each of the [tag] and [/tag] pairings, right? e.g. you want to extract "JAAN JOHN" Commented Aug 16, 2014 at 10:37
  • Yes, you are right Utkanos. I meant this Commented Aug 16, 2014 at 10:38
  • It would help everyone (also future readers) to give an example output (what you want to get). Commented Aug 16, 2014 at 10:40

3 Answers 3

2

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);
Sign up to request clarification or add additional context in comments.

3 Comments

This is the first time in many years that I have seen backreferences used. That is very cool! ;)
I've updated my first post, please read again, Thank you for your time sir!
Thank you sir! Your answer have solved my question, I'll select your answer as the best one. Thanks for all others.
1

This regex will do for each line.

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

Test the regex here.

1 Comment

I've updated my first post, please read again, Thank you for your time sir!
1

Use Lookahead and Lookbehind Assertions

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

See this demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.