dongmangji0950 2015-05-16 19:13
浏览 44
已采纳

PHP - 替换撇号

I am currently developing a website with a list of names. Some of the names include apostrophes ' and I want to link them to a website using their name.

I want to link to the a url like: example.com/ (their name)

And by doing that, I first replace " " with "+". So the links looks like: example.com/john+doe

But if the name is John'Doe it turns the url into just example.com/john

And skips the lastname.

How can I fix this? I tried changing ', \' etc, to html codes, to ', and more, but nothing seems to work.

Here is my current code:

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

What I want it to look like:

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

It changes the spaces to +, but how can I fix the apostrophes? Anyone knows?

  • 写回答

2条回答 默认 最新

  • dougan4663 2015-05-16 19:27
    关注

    You should be using PHP's function 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>";
    

    Output:

    <td>John%27Doe+Johnson <a href='http://www.example.com/name=John%27Doe+Johnson' target='_blank'></a></td>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料