preg_replace help

Discussion in 'PHP' started by php-lover, Dec 2, 2009.

  1. #1
    Hi

    I've been trying to achieve this code but it doesn't work at all.:(

    Here's the code:

    $link = '<a href = 'home.php' class="[home.php]">home</a>';

    From the link above, I try to replace the [home.php] with my class name "active".

    I try this code:

    preg_replace('/\[*\]/', 'active', $link);

    But that code was not work at all, any idea?

    Thanks
     
    php-lover, Dec 2, 2009 IP
  2. vinpkl

    vinpkl Active Member

    Messages:
    899
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    58
    #2
    class name is never kept with .php

    it should be

    $link = '<a href = 'home.php' class="[home]">home</a>';
     
    vinpkl, Dec 2, 2009 IP
  3. unigogo

    unigogo Peon

    Messages:
    286
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Try this regular expression,

    $patten = "/\[.*\]/";

    preg_replace($patten, 'active', $link);
     
    unigogo, Dec 2, 2009 IP
  4. JAY6390

    JAY6390 Peon

    Messages:
    918
    Likes Received:
    31
    Best Answers:
    0
    Trophy Points:
    0
    #4
    I prefer not using the . unless absolutely necessary. the last solution would fail if there were two [home.php] links for example in the same text
    Use this instead
    $pattern = '/\[[^\]]+\]/';
    PHP:
     
    JAY6390, Dec 2, 2009 IP
  5. sloddl

    sloddl Peon

    Messages:
    13
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    it should work like this:

    preg_replace('/\[(.*)\]/', '$1', $link);
     
    sloddl, Dec 3, 2009 IP
  6. php-lover

    php-lover Active Member

    Messages:
    261
    Likes Received:
    21
    Best Answers:
    0
    Trophy Points:
    58
    #6
    Appriciated your response.

    'JAY6390' , 'sloddl' and 'unigogo' code work for me.

    Thanks guys,
    Cheers.
     
    php-lover, Dec 4, 2009 IP
  7. szalinski

    szalinski Peon

    Messages:
    341
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    0
    #7
    In the case of two [home.php], he could simply use the U modifier or .*? instead.
     
    szalinski, Dec 4, 2009 IP