PREG_REPLACE如果字符串以char X结尾,则最后一个X字符将其替换为Y字符

时间:2011-08-01 17:20:39

标签: php regex

如果字符串以character X结尾,我想用character Y替换该特定字符。

示例1

anything_number_alphabet_dashes_anythingX[END OF STRING]

anything_number_alphabet_dashes_anythingY[END OF STRING]

示例2

DontReplaceThis_X_JustOnlyThisLast_X[END OF STRING]

DontReplaceThis_X_JustOnlyThisLast_Y[END OF STRING]

我想在PHP中使用preg_replaceereg_replace

执行此操作

1 个答案:

答案 0 :(得分:8)

美元符号是字符串锚的结束,所以:

$new_str = preg_replace('/X$/', 'Y', $old_str);