Find, replace and print only a specific word from a string

Discussion in 'PHP' started by Kyriakos, Feb 21, 2013.

  1. #1
    hi,
    I have this string:
    $mystr = "<ul>bla bla bla bla...</ul>";
    Code (markup):
    I want to find the "</ul>" and replace it with "</table>" but to print only this and to exclude any other text before or after that. how i can do this?

    Thank in advance.
     
    Kyriakos, Feb 21, 2013 IP
  2. MyVodaFone

    MyVodaFone Well-Known Member

    Messages:
    1,048
    Likes Received:
    42
    Best Answers:
    10
    Trophy Points:
    195
    #2
    So you basically want to get rid of <ul>bla bla bla bla...</ul>
     
    MyVodaFone, Feb 21, 2013 IP
  3. Xavier2013

    Xavier2013 Peon

    Messages:
    10
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    1
    #3
    start with str_replace(). everything else you need is here http://php.net/manual/en/ref.strings.php​
     
    Xavier2013, Feb 21, 2013 IP
  4. Darkfortune

    Darkfortune Greenhorn

    Messages:
    5
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    11
    #4
    Best way to solve this is with the following code:
    $mystr = "<ul>bla bla bla bla...</ul>";
    $mystr = str_replace(array('<ul>', '</ul>'), array('<table>', '</table>'), $mystr);
    PHP:
    Or if you only want the </ul>:

    $mystr = "<ul>bla bla bla bla...</ul>";
    $mystr = str_replace('</ul>', '</table>', $mystr);
    PHP:
     
    Darkfortune, Feb 26, 2013 IP
  5. iitstudent

    iitstudent Banned

    Messages:
    43
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    23
    #5
    You can use following function to find and replace
    
    <?php
    function str_replace_once($search, $replace, $subject) {
        $firstChar = strpos($subject, $search);
        if($firstChar !== false) {
            $beforeStr = substr($subject,0,$firstChar);
            $afterStr = substr($subject, $firstChar + strlen($search));
            return $beforeStr.$replace.$afterStr;
        } else {
            return $subject;
        }
    }
    ?>
    PHP:
     
    iitstudent, Feb 26, 2013 IP
    technoguy likes this.