I need to extract a string from a string

Discussion in 'PHP' started by jc@ukzone.com, May 30, 2008.

  1. #1
    I need to extract a word from a string and then add it to the end of the string.
    e.g.
    $name = "The Smokey Boys"
    I need to change this to:
    $name = "Smokey Boys, The"

    Up to now I have used:
    $temp = split(" ",$name);
    if ($temp[0] == "The ") $name = $name - $temp[0];
    $name = $name . ", " . $temp[0];

    This returns:
    "The Smokey Boys, The"
    which means that the first "The" is not being removed.

    Can anybodt advise me how to solve this problem.

    Thanks

    John C
     
    jc@ukzone.com, May 30, 2008 IP
  2. Freud2002

    Freud2002 Peon

    Messages:
    29
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #2
    The following line :
    $name = $name - $temp[0];

    is not correct, as - is a mathematical operation.
    So you should replace it by :
    $name = substr($name, 4, strlen($name) - 4);
     
    Freud2002, May 30, 2008 IP
  3. saurabhj

    saurabhj Banned

    Messages:
    3,459
    Likes Received:
    61
    Best Answers:
    0
    Trophy Points:
    0
    #3
    You can use substr for this.
     
    saurabhj, May 30, 2008 IP
  4. jc@ukzone.com

    jc@ukzone.com Guest

    Messages:
    35
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Many thanks for such quick relpies.
    I have now solved the problem with this bit of code:

    $temp = split(" ",$name);
    if ($temp[0] == "The")
    {
    $name = substr($name, 4, strlen($name) - 4);
    $name = $name . ", " . $temp[0];
    }

    Can anybodt forsee any problems with this ???

    I now need to know how to make the "The" case insensitive.
    Can anybody help with this ??

    Thanks,

    John C
     
    jc@ukzone.com, May 30, 2008 IP
  5. Freud2002

    Freud2002 Peon

    Messages:
    29
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Hello,

    just replace your actual if by :

    if (strtolower($temp[0]) == "the")

    to make it case insensitive.
     
    Freud2002, May 30, 2008 IP
  6. jc@ukzone.com

    jc@ukzone.com Guest

    Messages:
    35
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #6
    Many thanks Freud2002...
    I have now got what I was looking for.
    Your help very much appreciated - THANKS

    John C
     
    jc@ukzone.com, May 30, 2008 IP
  7. chicagoweb

    chicagoweb Peon

    Messages:
    30
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #7
    Also, take a look at substr_replace()
     
    chicagoweb, May 30, 2008 IP