Search code examples
phpstringurlreplaceapostrophe

PHP - Replace apostrophe


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?


Solution

  • 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>