Kareem Nour Emam
Kareem Nour Emam

Reputation: 1054

How to change only the last letter in a word using PHP's preg_replace?

I want know how to use preg_replace to change A - when it is the last letter - to e.
For example, I want to change the word "karema" to "kareme" - notice only the last a has changed, not the one in the middle!

Upvotes: 1

Views: 977

Answers (3)

Kobi
Kobi

Reputation: 138027

For changing "a" at the end of every word, use a\b:

preg_replace("/a\b/", "e", $str);

\b is a word boundary, it would work well in your case.

Example: http://ideone.com/ehN43

If your string is a single word you may also use a$ - the a at the end of the line.

Upvotes: 5

shankhan
shankhan

Reputation: 6571

This will work for you

preg_replace('/a\s/i', 'e ', 'This is some sample text karama dharama');

It will replace karama to karame and dhrama to dharame

Upvotes: 0

Michael Mior
Michael Mior

Reputation: 28762

If it's only that specific word, you don't need preg_replace. Simply use str_replace('karema', 'kareme', $TEXT_TO_BE_CHANGED). If this isn't what you want, you'll have to provide a more detailed example of what you're looking for.

Upvotes: 0

Related Questions