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


Replace a single quote ( ' ) with another quote (’) str_replace

我正在尝试用另一个引号((替换单引号('(,但我似乎无法正常工作。另外,我怎样才能在多个字符串上工作($text, $title, $notice)

输入:不要

输出:不要

我正在尝试这个:

$text = str_replace(array("'",'"'), array('’'), $text);    
$text = htmlentities(str_replace(array('"', "'"), '’', $text);
$text = htmlentities(str_replace(array('"', "'"), '’', $_POST['text']));
$text = str_replace("'" ,"’",$text);
$text = str_replace("'" ,"’",$text);
$text = str_replace(array("'"), "’", $text);
$text = str_replace(array("''", "'", """), "’", htmlspecialchars($text));
$text = str_replace(array('''', '"'), '’', $text);
$text = str_replace(chr(39), chr(146), $text);
$text  = str_replace("'", "&ampquot;", $text); 

这些都行不通。

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

<?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";
?>

我尝试使用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’

试一试。