Solved

Extracting tags from a string using regular expressions

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

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Both Easy and Powerful How easy is PHP? http://lmgtfy.com?q=how+easy+is+php (http://lmgtfy.com?q=how+easy+is+php)  Very easy.  It has been described as "a programming language even my grandmother can use." How powerful is PHP?  http://en.wikiped…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…

746 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

12 Experts available now in Live!

Get 1:1 Help Now