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?

图片转代码服务由CSDN问答提供 功能建议

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

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

通过这样做,我首先用“+”替换“”。 所以这些链接如下所示:example.com/john+doe

nn

但如果名称是John'Doe,它会将url变为example.com/john \ n

并跳过姓氏。

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

这是我当前的代码:

  $ name = $ row ['name']; 
 $ new_name = str_replace(
 array(“'”,“&amp;#  39;“),
 array(”“,”+“),
 $ name 
); 
 
echo”&lt; td&gt;“  。  $ name。  “&lt; a href ='http://www.example.com/name=”。  $ new_name。  “'target ='_ blank'&gt;&lt; / a&gt;”  。  “&lt; / td&gt;”; 
   
 
 

我希望它看起来像:

  John Doe Johnson  ----&GT;  http://www.example.com/name=John+Doe+Johnson
John'Doe Johnson ----&gt;  http://www.example.com/name=John'Doe+Johnson
nn

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

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

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>
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dongyanhu5628 2015-05-16 19:27
    echo urlencode("John'Doe Johnson");
    

    return

    John%27Doe+Johnson
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题