【问题标题】:Changing normal quotes to curly ones in php在php中将普通引号更改为大引号
【发布时间】:2019-09-05 12:30:34
【问题描述】:

我正在尝试在 PHP 中将直引号 ("something") 更改为花引号 („something")。其他答案不适合我的情况,因为我有一个从 DB 导入的产品详细信息作为 variable,使用 str_replace 我设法只将其更改为 并且它似乎我无法将第二个更改为 。据我所知,没有办法做到这一点。

例如:

$description 输出 -> 大家好,我想将这个直“引号”“更改”为“卷曲”。

我想要什么:

$description 输出 -> “大家好”,我想将这个直“引号”“更改”为“卷曲”。

【问题讨论】:

  • 我可能错了,但“卷曲”引号不只是一种字体样式吗?
  • 不是,可以通过在css中指定q {quotes: "„" """;} 来完成。但是我们有一个定制的 CMS,其中至少有 15 - 20k 种产品。想象一下,将每个产品从直接更改为

标签: php html regex


【解决方案1】:

尝试将preg_replace"(.*?)" 模式一起使用。然后,用大括号内的捕获组$1 替换。

$input = "Hello \"everyone\", I would like to \"change\" this straight \"quotes\" to \"curly\" ones.";
$output = preg_replace("/\"(.*?)\"/", "„$1“", $input);
echo $output;

打印出来:

Hello „everyone“, I would like to „change“ this straight „quotes“ to „curly“ ones.

编辑:

您正在尝试替换已编码双引号的 HTML 代码,因此请尝试以下操作:

$input = "Exklusiv von buttinette: Baumwollstoff "Leo",";
$output = preg_replace("/"(.*?)"/", "“$1”", $input);
echo $output;

打印出来:

Exklusiv von buttinette: Baumwollstoff “Leo”,

【讨论】:

  • 它不会改变任何东西。也许是因为直引号只是“,没有\。
  • @asobak 在 PHP 字符串中使用双引号表示的文字双引号需要使用反斜杠进行转义。我的代码正在处理您在问题中提供的示例数据。
  • 没错,我知道。但不应该有不工作的理由。我已经尝试过类似的方法,但我的目标是用引号插入一个单词..
  • 然后给我我的答案失败的示例数据。
  • 您在 HTML 文本上执行此操作,而不是渲染输出。试试我更新的答案。
【解决方案2】:

使用explodearray_reduce

$str = 'Hello "everyone", I would like to "change" this straight "quotes" to "curly" ones.';

$parts = explode('"', $str); // or  explode('"', $str);
$carry = array_shift($parts);

$result = array_reduce($parts, function ($c,$i) {
    static $up = false;
    return $c . ((true === $up=!$up) ? '„' : '“') . $i;
}, $carry) ;

demo

显然,如果您的原始引号是 html 实体,您必须更改 explode 的第一个参数。


使用strtok

$str = 'Hello "everyone", I would like to "change" this straight "quotes" to "curly" ones.';

$result = substr(strtok(".$str", '"'), 1);

while (false !== $part = strtok('"')) {
    $result .= "„${part}“" . strtok('"');
}

demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2014-10-23
    相关资源
    最近更新 更多