PHP - 替换撇号

时间:2015-05-16 19:13:27

标签: php string url replace apostrophe

我目前正在开发一个包含名单的网站。一些名称包括撇号',我想用他们的名字将它们链接到一个网站。

我想链接到一个网址: example.com/(他们的名字)

通过这样做,我首先用“+”替换“”。所以链接看起来像:example.com/john+doe

但如果名字是John'Doe,它会将网址改为example.com/john

跳过姓氏。

我该如何解决这个问题?我尝试将'\'等更改为html代码,更改为“等等,但似乎没有任何效果。

这是我目前的代码:

$name = $row['name'];
$new_name = str_replace(
    array("'", "'"),
    array(" ", "+"),
    $name
);

echo "<td>" . $name . " <a href='http://www.example.com/name=" . $new_name . "' target='_blank'></a>" . "</td>";

我希望它看起来像:

John Doe Johnson ----> http://www.example.com/name=John+Doe+Johnson
John'Doe Johnson ----> http://www.example.com/name=John'Doe+Johnson

它将空格更改为+,但如何修复撇号?有人知道吗?

2 个答案:

答案 0 :(得分:2)

echo urlencode("John'Doe Johnson");

返回

John%27Doe+Johnson

答案 1 :(得分:2)

你应该使用PHP的函数urlencode,php.net / manual / en / function.urlencode.php。

<?php
$name = $row['name'];
//$urlname = urlencode('John\'Doe Johnson');
$urlname = urlencode($name);
echo "<td>$name<a href='http://www.example.com/name=$urlname' target='_blank'>$name</a></td>";

输出:

<td>John%27Doe+Johnson <a href='http://www.example.com/name=John%27Doe+Johnson' target='_blank'></a></td>
相关问题