Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New Coder
    Join Date
    Jan 2006
    Location
    Oslo, Norway
    Posts
    86
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Simple regexp (or so I think)

    But I'm new at this regexp-thing:S

    Say I got the following:
    $text = "Hi, how are <tag>you <b>my</b> friend?</tag>";

    1. How do I get hold of the content of the tag? (That which is between <tag> and </tag>.)

    2. And then I would like to replace "<tag>you <b>my</b> friend?</tag>" with "another text".

    If someone who can this wonderful, but jet difficult, regexp stuff could help me?

    Regards and thanks!
    Drømmejenta: Kristen jente som progger Python!

  • #2
    Regular Coder
    Join Date
    Sep 2005
    Posts
    394
    Thanks
    1
    Thanked 0 Times in 0 Posts
    PHP Code:
    <?php
    $text 
    "Hi, how are <tag>you <b>my</b> friend?</tag>";
    preg_match("@(\<tag\>).*(?=\<\/tag\>)@"$text$match);
    echo 
    substr($match[0], 5); //echos "you <b>my</b> friend?"
    $text str_replace($match[0] . '</tag>''another text'$text);
    echo 
    $text//echos "Hi, how are another text"
    ?>
    ~Phil~
    Last edited by lavinpj1; 06-20-2006 at 05:49 PM.

  • #3
    New Coder
    Join Date
    Jan 2006
    Location
    Oslo, Norway
    Posts
    86
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Hi, I messed around a little bit, and came up with something that seems to work:
    PHP Code:
    $text "Hi, how are <tag>you <b>my</b> friend?</tag>";
    $match = array(); 
    preg_match("/<tag>(.*)<\/tag>/i"$text$match);
    echo 
    $match[1];
    echo  
    preg_replace("/<tag>(.*)<\/tag>/i""another text"$text); 
    Is this doing the same as lavinpj1, or am I missing something important? It echoes the same for the example.

    Question:
    preg_match("@(\<tag\>).*(?=\<\/tag\>)@", $text, $match);
    What does the "@" means, and is is necessary to escape the "<" and ">"?
    Drømmejenta: Kristen jente som progger Python!


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •