Replace items in the string for the exception of the last occurance

I have the following code which grabs a the categories from my wordpress blog and replaces all the line breaks with a pipe.

<?php $variable = wp_list_categories('style=none&echo=0'); ?>
<?php $variable = str_replace('<br />', ' | ', $variable); ?>
<?php echo $variable; ?>

The code works – however I need the last occurrence to be ignored.
Any way around this?

Read More

Thanks!

Related posts

Leave a Reply

3 comments

  1. Another way would be to get the last pipe | character with strrpos, once found, just remove it using the string index, then use a substr_replace and replace it with a <br/> again:

    $variable = str_replace(array('<br/>', '<br />', '<br>'), '|', $variable);
    $last_pipe = strrpos($variable, '|');
    if($last_pipe !== false) {
        $variable[$last_pipe] = ''; // remove
        $variable = substr_replace($variable, '<br/>', $last_pipe, 0); // replace
    }
    echo $variable;
    

    Sample Output

    Sidenote: This would be the dirty solution to it, but if you have more complex operations to be done, it might be better to just use HTML Parsers with this one, DOMDocument in particular in conjunction with ->replaceChild with regression.

    $dom = new DOMDocument;
    $dom->loadHTML($variable, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
    $br_tags = $dom->getElementsByTagName('br');
    $i = $br_tags->length - 2; // -2 to leave the last one conversion
    while($i > -1) {
        $br = $br_tags->item($i);
        $pipe = $dom->createTextNode('|');
        $br->parentNode->replaceChild($pipe, $br);
        $i--;
    }
    
    echo $dom->saveHTML();
    

    Sample Output

  2. Try with rtrim(). It will remove the last | from the string.

    echo rtrim($variable, '|');
    

    Update

    $str = "hhh|yyy|YY|ll";
    $last = strrpos($str, '|');
    $part = rtrim(substr($str, 0, $last), '|');
    if($last < strlen($str))
        $part .= substr($str, $last + 1), (strlen($str) -$last));
    
    echo $part;
    
  3. When using str_replace with category variable it return categories | pipe seprated with space before category name

    so you can remove last two characters one with space and second is | pipe.

    $variable = wp_list_categories('style=none&echo=0'); 
    $variable = str_replace('<br />', '|', $variable);
    var_dump($variable);
    echo substr($variable,0,strlen($variable)-2);
    

    if you use Pipe with spaces before and after the category name then use -4 instead -2