1

File:

C:\Some\Location\index

I just want to replace \index with \example

echo preg_replace('/[\\\|\/]{1}.*?$/', '\example', $file);

It just keeps being too greedy. I don't know of any modifiers that would help that problem.

Thanks!

5 Answers 5

4

how about echo preg_replace('/[\\\|\/]{1}[^\\\/]*?$/', '\example', $file); ?

Sign up to request clarification or add additional context in comments.

Comments

3

Replace the . with [^/\], which matches anything but the slashes. I also changed the regex delimiter to @, since slashes aren't appropriate when handling paths.

$str='C:\\Some\\Location\\index';
echo preg_replace('@[/\\\\][^/\\\\]+$@', '\example', $str);
# echoes: C:\Some\Location\example

Comments

2

You don't need a regex for that if you can use forward slashes instead of those ugly backslashes (yes, windows does support forward slashes):

$str = 'C:/Some/Location/index';
echo dirname($str).'/example';

3 Comments

Well, I can't assume that any platform uses one or the other as far as slashes go, unless I'm replacing slashes, but that seems unnecessary. @simon, I think regular expressions are very appropriate here.
@Senica - to perform path manipulation? I'm gonna stick to my original opinion.
You do not need backslashes on any platform. Forward slashes are the way to go. They work on Linux/Unix, OSX and Windows - and probably on most/all exotic systems.
1
preg_replace( '/(^.*?)\\([^\\]+)$/', '$1\\example', $file );

And a RegExp-less solution:

$path = explode( '\\', $file );
array_splice( $path, -1, 1, 'example' )
$file = implode( '\\', $path );

Comments

1

If you insist on using regular expressions,

 echo preg_replace('/[^\/\\]*$/', 'example', $file) 

will do.

I recommend using

 echo dirname($file).'\example'

instead, which will safely handle forward and backslashes, the root directory etc.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.