Frank Smith
Frank Smith

Reputation: 119

avoid PHP case sensitivity on replace function

I have the following code use to show the thumbnail of an image, the thumbnail is create with _small placed at the end of the file name. Its a simple replace function:

<?php
if ($row_rsAdminMenu['image1']) {
    $src = $row_rsAdminMenu['image1'];
    $src = str_replace('.JPG', '_small.JPG', $src);
} else {
    $src = '../../images/NoPic.jpg';
}
echo '<img src="' . htmlspecialchars($src, ENT_COMPAT, 'UTF-8') . '" />'; ?>

Upvotes: 1

Views: 53

Answers (3)

mhawke
mhawke

Reputation: 87074

It was not very clear in the question, but I think that you want to be able to alter the filename as follows:

image.JPG -> image_small.JPG
image.jpg -> image_small.jpg

This can be done using preg_replace() using back references, for example:

php > echo preg_replace('/(^.*)(\.jpg)$/i', '\1_small\2', 'image.jpg');
image_small.jpg
php > echo preg_replace('/(^.*)(\.jpg)$/i', '\1_small\2', 'image.JPG');
image_small.JPG
php > echo preg_replace('/(^.*)(\.jpg)$/i', '\1_small\2', 'image.jPg');
image_small.jPg

This works by inserting "_small" between the 2 matched groups.

In the context of your code:

<?php
if ($row_rsAdminMenu['image1']) {
    $src = $row_rsAdminMenu['image1'];
    $src = preg_replace('/(^.*)(\.jpg)$/i', '\1_small\2', $src);
} else {
    $src = '../../images/NoPic.jpg';
}
echo '<img src="' . htmlspecialchars($src, ENT_COMPAT, 'UTF-8') . '" />'; ?>

With a minor modification it can also work for other file extensions if desired:

php > echo preg_replace('/(^.*)(\.(jpg|gif|png|jpeg))$/i', '\1_small\2', 'image.PNG');
image_small.PNG

Upvotes: 1

Sougata Bose
Sougata Bose

Reputation: 31749

Try with -

echo preg_replace('/.jpg/i', '', '_small.JPG');

Or if want to remove multiple extensions -

echo preg_replace('/.(jpg|gif|png)/i', '', '_small.JPG  _small.GIF');

Upvotes: 0

Iswanto San
Iswanto San

Reputation: 18569

You can use str_ireplace for case insensitive replace.

 $src = str_ireplace('.JPG', '_small.JPG', $src);

Upvotes: 1

Related Questions