Solved

Extracting tags from a string using regular expressions

Posted on 2011-02-17
2
313 Views
Last Modified: 2012-08-13
Hello experts,

I have a string like....

<this>my name is <name>jonny</name><br/>i am <age>26</age></this>

I am trying to output an array like this...

[0]=<this>
[1]=my name is
[2]=<name>
[3]=jonny
[4]=</name>
[5]=<br/>
[6]=i am
[7]=<age>
[8]=26
[9]=</age>
[10]=</this>

So each tag is in a new array element and the plain text is in its own array element

i have been messing around with regular expressions to try to extract it correctly but am just getting angry...

Does anyone have any ideas?
Thanks
0
Comment
Question by:handypam
2 Comments
 
LVL 35

Accepted Solution

by:
Terry Woods earned 250 total points
ID: 34920382
$sourcestring="your source string";
preg_match_all('/<[^>]*>|[^<>]+/',$sourcestring,$matches);
echo "<pre>".print_r($matches,true);

Result:
    [0] => Array
        (
            [0] => <this>
            [1] => my name is
            [2] => <name>
            [3] => jonny
            [4] => </name>
            [5] => <br/>
            [6] => i am
            [7] => <age>
            [8] => 26
            [9] => </age>
            [10] => </this>
        )
0
 

Author Comment

by:handypam
ID: 34920400
PERFECT THANKS!
0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
This article discusses four methods for overlaying images in a container on a web page
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question