find string

Discussion in 'PHP' started by snowLee, May 16, 2009.

  1. #1
    I have this code:

    $var = "This is my website <a href=\"index.php\">My website</a> and I want to see your opinion";
    echo $var;

    I want to look in the variable $var and search for <a . When I find this <a I to take what is between this <a and </a> and put it into a different variable, $var2.

    Can someone, please, tell me how can I do this?
     
    snowLee, May 16, 2009 IP
  2. JDevereux

    JDevereux Peon

    Messages:
    50
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #2
    This may work:

    <?php
    $var = "This is my website <a href=\"index.php\">My website</a> and I want to see your opinion";
    preg_match('/<a(.*?)<\/a>/', $var, $goodies);
    $var2 = $goodies[1];
    echo $var2;
    ?>
    PHP:
     
    JDevereux, May 16, 2009 IP
  3. xxKillswitch

    xxKillswitch Peon

    Messages:
    331
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Regex would work, as well as using a complicated mixture of built in functions. Use strpos first to see if there is an anchor at all in the var your checking...

    
    if(strpos($var, '<a') !== false) {
         // Run regex here for match
    }
    
    Code (markup):
     
    xxKillswitch, May 17, 2009 IP
  4. iRobit

    iRobit Peon

    Messages:
    133
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    :D
    
    <?php
    $var = "This is my website <a href=\"index.php\">My website</a> ";
    $out=explode("<a",$var);
    $out2 = explode("</a>",$out[1]);
    $result = out2[0];
    ?>
    
    PHP:
     
    iRobit, May 18, 2009 IP