php - 替换字符串以匹配复数或单数

标签 php regex string

你能帮我用一个函数来替换字符串吗?

字符串 the boo[k|ks] [is|are] on the table 将输出 the book is on the tablethe books are on表根据参数。

<?php
    $unformated_str = "the boo[k|ks] [is|are] on the table";
    $plural = true;

    echo formatstr($unformated_str, $plural);
?>

输出:

the books are on the table

请原谅我糟糕的英语。我希望我的问题足够清楚。

最佳答案

这是一个使用 preg_replace_callback() 的函数:

function formatstr( $unformatted_str, $plural) {
    return preg_replace_callback( '#\[([^\]]+)\]#i', function( $match) use ($plural) {
        $choices = explode( '|', $match[1]);
        return ( $plural) ? $choices[1] : $choices[0];
    }, $unformatted_str);
}

$unformated_str = "the boo[k|ks] [is|are] on the table";

echo formatstr($unformated_str, false); // the book is on the table
echo formatstr($unformated_str, true); // the books are on the table

Try it out

关于php - 替换字符串以匹配复数或单数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11143194/

相关文章:

php - 使用包含 GET url 的参数的 CURL Get 请求

python - 否定正则表达式的一部分

正则表达式从路径中删除文件名

java - Java 字符串对象是字符数组吗?

java - 字符串拆分为两个列表

string - shell 中字符串的小写 + 大写 + 连接单词(例如 bash)

php - 我做错了吗,或者在使用数组作为字段名称时 CodeIgniter 表单验证库中是否存在错误?

php - session id如何找到当前用户id

php - 抛出异常以返回服务器错误是否不好,例如。 404页面不存在?

regex - 如何使用 Notepad++(正则表达式)选择注释之间的所有代码