basic string replacement

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
If I have a string such as "/ Support us / Volunteering" how do I get  
rid of the first slash and not both of them? I had a go at ltrim but  
with no success. $path = ltrim($path, "/")


Re: basic string replacement

Gonzillaaa wrote:

Quoted text here. Click to load it



Justin Koivisto, ZCE -

Re: basic string replacement

Thanks Justin  

I've always found regular expression intimidating.

Re: basic string replacement

I was always surprised that PHP didn't have a "limit" argument for
str_replace() that would limit the number of replacements made.  If
anyone is interested, I wrote this guy.  There's probably a better way,
but it seems to work:

function str_replace_limit($search, $replace, $subject, $limit, &$count
= null) {
    $count = 0;

    if($limit == 0 || strpos($subject, $search) === false)
        return $subject;

    $pos = 0;
    for($i = 0; $i < $limit; $i++) {
        $pos = strpos($subject, $search, $pos);
        if($pos === false)
            return str_replace($search, $replace, $subject, $count);

        $pos += strlen($search);

    $count = $limit;
    $pre = str_replace($search, $replace, substr($subject, 0, $pos));
    $post = substr($subject, $pos);
    return $pre . $post;
} //str_replace_limit

Site Timeline