用另一个引号(')str_replace替换单引号(')

时间:2016-05-08 14:11:55

标签: php string replace str-replace htmlspecialchars

我正在尝试用另一个引号({1: [1, 2, 3, 4], 2: [1, 2, 3, 4]} {1: [1, 1], 2: [2, 2], 3: [3, 3], 4: [4, 4]} )替换单引号('),但我似乎无法正常工作。 另外,如何在多个字符串上进行此工作?

  

输入:不要

     

输出:不要

我正在尝试这个:

($text, $title, $notice)

这些都不起作用。

2 个答案:

答案 0 :(得分:5)

当您使用阵列作为替换时,请提供与针一样多的替换。否则使用简单的字符串。

<?php
$text = 'Peter\'s cat\'s name is "Tom".';
$text = str_replace(array("'",'"'), '’', $text);  
echo $text;

$text = 'Peter\'s cat\'s name is "Tom".';
$text = str_replace(array("'",'"'), array('’', '`'), $text);  
echo $text;
?>

要对您可以执行的多个变量执行该任务

<?php
$text   = 'Peter\'s cat\'s name is "Tom".';
$title  = 'Peter\'s cat\'s name is "Tom".';
$notice = 'Peter\'s cat\'s name is "Tom".';

foreach([&$text, &$title, &$notice] as &$item)
  $item = str_replace(array("'",'"'), '’', $item);  

echo "text: $text<br>title: $title<br>notice: $notice";
?>

答案 1 :(得分:1)

我尝试使用preg_replace()并且第一次完美运行:

$text = "Someone told me about a 'bacon and cheese sandwich'";
$text = preg_replace("#\'#", '’', $text);
echo $text;

输出
Someone told me about a ’bacon and cheese sandwich’

放手一搏。

相关问题