views:

70

answers:

4

Hi, how can change only the last letter of any word of a string with regular expressions?

I use mb_strtolower() for change strings from upper to lower in Greek language and I have problem with final 's'.

+1  A: 
preg_replace (‘/σ\b/’, ‘ς’, $cat_name);
SilentGhost
I'm afraid this doesn't work.
Artefacto
@Artefacto: works just fine for me.
SilentGhost
@SilentGhost Test script, please. See this: http://codepad.viper-7.com/rQXrQc
Artefacto
+2  A: 

Use a word boundary -- \b -- to match the start or end of a word. Try

preg_replace ('/σ\b/', 'ς', $cat_name);
Andy E
Either I'm doing something very wrong, or, with everything in UTF-8, the preg_replace gives me an empty string. Handling of UTF-8 string requires the 'u' modifier, but even there the support is only partial.
Artefacto
A: 

EDIT2:

mb_internal_encoding("UTF-8");
$s = "sdfΣ";
echo $s,"\n";
echo mb_ereg_replace("Σ\\b", 'ς', $s);

EDIT: Apparently, this doesn't work for greek leters, preg_replace will match "f", not the sigma.

Not that I know any greek, but σ is labelled as "Greek small letter sigma", so you ask for the lowercase version, it should still give σ.

mb_strtolower() should work. You're probably doing something wrong. Post the relevant portion of your program.

Anyway, with preg_replace and assuming both your script and $cat_name are encoded in UTF-8, it's:

echo preg_replace ("/\\w\\b/eu", 'mb_strtolower(\'\\0\', \'UTF-8\')', $cat_name);

for instance, if $cat_name == "sdfÉ", this gives sdfé.

Artefacto
The problem is that uppercase sigma has two lowercase variants depending on the position within the word. So `mb_strtolower()` works halfway - it's not smart enough to handle the disambiguation.
Tim Pietzcker
@Tim OK, nice to know. So I guess the OP was just converting everything to `σ` and then wanted to replace the sigmas in the end of the words with `ς`.
Artefacto
A: 

The code that I use is: mb_internal_encoding("ISO-8859-7"); $cat_name=mb_strtolower($categories_name); $cat_name=preg_replace('/σ\b/', 'ς', $cat_name);

The problem is that when I use $cat_name=preg_replace('/σ/', 'ς', $cat_name); work right and replace every 'σ' with 'ς'

My server has PHP 5.2.6-1+lenny8 with Suhosin-Patch 0.9.6.2 (cli) (built: Mar 14 2010 09:07:33)

Local in my laptop I use Xamp for windows with PHP Version 5.3.1 and the switch \b work. So the problem is in the different version of Php or in php.ini ?

Thanks for the replies..

Sgr