Jump to content

replace last ocurrence


ToonMariner

Recommended Posts

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]
Link to comment
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]
Link to comment
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 '/'
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.