douyan1244 2013-09-06 12:03
浏览 30
已采纳

使用preg_replace使序数以小写形式出现

I have a column of address data that has ordinals displayed like this:

3Rd Floor, Cumbrian House

Room 223, 2Nd Floor

when I would like them to be displayed like this instead:

3rd Floor, Cumbrian House

Room 223, 2nd Floor

I'm trying to make use of the preg_replace function to swap out a capitalised letter, that directly follows a number, with a lower case letter instead. (I admit this is my first time using the preg_replace function. I am however fine with preg_match and regular expressions).

So far I have:

$string = '3Rd Floor, Cumbrian House';

$ordinalregex = '/(^.*\d+)([A-Z])/';
$correctordinal = '$1'.strtolower('$2');

echo preg_replace($ordinalregex,$correctordinal,$string)."<br>";

But its not having the desired effect and outputs the line exactly as it first appeared.

Thanks

  • 写回答

2条回答 默认 最新

  • douba3975 2013-09-06 12:14
    关注

    I think you need to use preg_replace_callback as I'm not sure you can replace based on the part you matches in normal preg_replace. What you need to do is use a callback function that takes the matches array and processes it (you could also just use preg_match and then work with the matches seperetaly).

    This example works (although it uses an anonymous function for the callback, which requires PHP 5.3.0+):

    function fixOrdinals($string) { 
        return preg_replace_callback("/[0-9][A-Z]/",
            function ($matches) { 
                return strtolower($matches[0]);
            },
            $string
        );
    }
    
    echo fixOrdinals("3Rd Floor, Cumbrian House")."
    ";
    echo fixOrdinals("Room 223, 2Nd Floor")."
    ";
    echo fixOrdinals("4Th Room, 2Nd Floor")."
    ";
    

    Output:

    3rd Floor, Cumbrian House
    Room 223, 2nd Floor
    4th Room, 2nd Floor
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?