Domanda

I'm trying to add something in the MIDDLE of a text, like that.

PrivateImg-0123456789_[I wanna add here something].jpg

And I don't know which function or way should I use.

I was wondering about the function preg_replace, but I don't know if you can make this function replace a specific text in some position.

È stato utile?

Soluzione 3

Just use str_replace()?

$string = "PrivateImg-0123456789.jpg";
echo str_replace(".jpg", "[whateveryouwant].jpg", $string);

If you must use regex:

$string = "PrivateImg-0123456789.jpg";
echo preg_replace("/\.(jpe?g|png|gif)$/si", "[whateveryouwant].$1", $string);

This will do jpg, jpeg, png and gif, as long as it is the last part. /foo/bar.gif/thisIsWeird wont match

Altri suggerimenti

Try this, if you want to insert the text just before the extension :

$string = 'PrivateImg-0123456789.jpg';
$pattern = '/(.+?)(\.[^\.]+)/';
$text_to_insert = '_I wanna add here something';
$replacement = '${1}' . $text_to_insert . '$2';
echo preg_replace($pattern, $replacement, $string);

The pattern says : (.+?) match and group any character except \n 1 or more times

then (.[^.]+) match and group . character '.' and any character except: '.' 1 or more times

What about this code without using preg_replace. Might a one/tow more lines of code, but definitely easier than preg_replace solution

<?php
$string = 'PrivateImg-0123456789.jpg';
$text_to_insert = '_I wanna add here something';
$pos = strrpos($string,".");
$string = substr($string,0,$pos) . $text_to_insert . substr($string,$pos);
print $string;
?>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top