Jump to content

Archived

This topic is now archived and is closed to further replies.

ToonMariner

replace last ocurrence

Recommended Posts

OK I got writers block...

I know this is easy.

have a string of a full path to a file want to replace the last '/' with '/thumb/'

sure i can user just str_replace for this but i just can't think

PS please sympatize! I did the Great North Run yesterday!!!!

Share this post


Link to post
Share on other sites
The[tt] .+ [/tt] is greedy and gobbles everything. The engine then gives everything back until it finds a / (which would be the last one).
[code]
$string = '/path/to/image/dir/';
echo preg_replace('%(.+)/%', '\1/thumb/', $string);
[/code]

Share this post


Link to post
Share on other sites
[quote author=effigy link=topic=110239.msg445316#msg445316 date=1159803770]
The[tt] .+ [/tt] is greedy and gobbles everything. The engine then gives everything back until it finds a / (which would be the last one).
[code]
$string = '/path/to/image/dir/';
echo preg_replace('%(.+)/%', '\1/thumb/', $string);
[/code]
[/quote]

with that being said, do you think it would be safer to use [tt].*[/tt] in case you're matching a root level directory?
[code]
<?php
$string = '/';
echo preg_replace('|(.*)/|', '\1/thumb/', $string);
?>
[/code]

Share this post


Link to post
Share on other sites
[quote author=effigy link=topic=110239.msg445409#msg445409 date=1159809933]
Good catch.
[/quote]

thanks... not often i have one of those with regex ;)

Share this post


Link to post
Share on other sites
you want to replace the last / of your path to /thumb/ ?

why dont you just [b]thumb/[/b] to the end of the path?
[code]$string = '/path/to/image/dir/';
echo $string . 'thumb/'; // ouput: /path/to/image/dir/thumb/[/code]

Share this post


Link to post
Share on other sites
[quote author=Nicklas link=topic=110239.msg445494#msg445494 date=1159814971]
you want to replace the last / of your path to /thumb/ ?

why dont you just [b]thumb/[/b] to the end of the path?
[code]$string = '/path/to/image/dir/';
echo $string . 'thumb/'; // ouput: /path/to/image/dir/thumb/[/code]
[/quote]

because your path may be referring to a specific file. for instance, if you grab the current URL and based on the location of the current file, you want to get the thumbnail directory, you'd want to start with the last slash, NOT with the end of the string. there are several instances where you'd want to use a check such as the regex that effigy provided as opposed to making assumptions that the path is always going to end with '/'

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.