Solved

Extracting tags from a string using regular expressions

Posted on 2011-02-17
2
302 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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

This article discusses four methods for overlaying images in a container on a web page
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
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 …

919 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

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now