PHP - Replace apostrophe - 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?

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>

echo urlencode("John'Doe Johnson");
return
John%27Doe+Johnson

Related

php echo string html with php-variables, can't break the php string

I'm trying to echo a phpstring-message. This php string consists of html and php variables and comes form a database and i can't change that data.
$name = 'John';
$str = '<b>Hi {$name},</b><br/>How are you?';
echo $str;
So i'm trying to replace the php string, but it doesn't work. This is my code:
$str = str_replace('{', '\' . ', $str);
$str = str_replace('}', ' . \' ', $str);
I get: <b>Hi' . $name. ',</b><br/>How are you?
How do i get the string like this?
<b>Hi John,</b><br/>How are you?
Thank you in advance
Just do it like this, you won't be able to replace it with a concatenation:
echo str_replace('{$name}', $name, $str);
EDIT:
If you don't know the name of the variable just use this:
echo preg_replace('/\{(.*?)\}/', $name, $str);
it's already implemented in PHP, you can directly write the variable in double quote like this:
echo "<b>Hi $name,</b><br/>How are you?";
or for some more complex variables:
echo "<b>Hi {$user->name},</b><br/>How are you?";

Can I use str_replace twice in one string?

<?php
echo "I'm currently listening to</a> <a href='http://last.fm/artist/" . str_replace(" ","+",$artist) . "/_/" . str_replace(" ","+",$currenttrack) . "'>" . $currenttrack . "</a>";
?>
Above is my code. I'm trying to use str_replace() again on $artist and $currenttrack like:
str_replace("'","%27",$artist) and str_replace("'","%27",$currenttrack)
because the apostrophe doesn't go through correctly and messes with my code, but when I use it first with the spaces, it's already passed and won't change again.
What can I do?
If you want to do multiple replacements on the same string, you can pass arrays to str_replace:
str_replace(array(" ", "'"), array("+", "%27"), $artist)
However, when creating URL parameters, you shouldn't do the replacements yourself. You should use urlencode, and it will do all the necessary encodings.
Try this. It also makes your code more readable. Also, your anchor tags aren't formatted correctly.
$artist = str_replace(' ', '+', $artist);
$track = str_replace(' ', '%27', $currenttrack);
echo 'I\'m currently listening to ' . $track . '';
If I understood your question correctly, you are trying to replace spaces by + and ' by %27 in the two strings. To achieve this, you have to apply str_replace() on the result of the first operation. If $input is the original string, use:
$intermediate = str_replace(" ", "+", $input);
$result = str_replace("'", "%27", $intermediate);
There is a built in function to do the same you are trying to do: urlencode
$currenttrack = $artist = "X' xx WWW' w";
$url = "http://last.fm/artist/" . $artist . "/_/" . $currenttrack;
echo urlencode($url); // http%3A%2F%2Flast.fm%2Fartist%2FX%27+xx+WWW%27+w%2F_%2FX%27+xx+WWW%27+w

addslashes not working for $_GET single quotes

I'm having issues with apostrophes in GET arrays. I can't seem to escape single quotes. I've trawled through similar SO topics for over a day now with no luck. I think this may be something to do with my connection to the database as if I make a plain unconnected php page both addslashes and str_replace successfully escape single quotes in GET variables (mysqli_real_escape_string doesn't since there is no database connection).
PHP 5.2.17
Mysql 5.5.23
Magic_quotes is off
The connection:
DEFINE ('database', 'dbname');
DEFINE ('user', 'dbusername');
DEFINE ('pass', 'dbpassword');
DEFINE ('host', 'localhost');
$dbc = #mysqli_connect (host, user, pass, database) OR die ('Could not connect to database: ' . mysqli_connect_error() );
The database appears to be connected, select queries involving GET variables that do not have single quotes in work fine. However, now when a GET containing a single quote is passed, I can't seem to escape it.
print_r($_GET);
echo "<br><br>";
$text = "O'Reilly";
echo "Normal variable called text: " . $text . "<br>
addslashes(): " . addslashes($text) . "<br>
mysqli_real_escape_string(): " . mysqli_real_escape_string($dbc, $text) . "<br>
str_replace(): " . str_replace("'", "\'", $text) . "<br>
<br>";
echo "_GET variable: " . $_GET['breed'] . "<br>
addslashes(): " . addslashes($_GET['breed']) . "<br>
mysqli_real_escape_string(): " . mysqli_real_escape_string($dbc, $_GET['breed']) . "<br>
str_replace(): " . str_replace("'", "\'", $_GET['breed']) . "<br>
<br>";
$_GET['breed'] = "O'Conner";
echo "_GET variable with new value: " . $_GET['breed'] . "<br>
addslashes(): " . addslashes($_GET['breed']) . "<br>
mysqli_real_escape_string(): " . mysqli_real_escape_string($dbc, $_GET['breed']) . "<br>
str_replace(): " . str_replace("'", "\'", $_GET['breed']) . "<br>
<br>";
gives:
Array ( [breed] => Cirneco dell'Etna )
Normal variable called text: O'Reilly
addslashes(): O\'Reilly
mysqli_real_escape_string(): O\'Reilly
str_replace(): O\'Reilly
_GET variable: Cirneco dell'Etna
addslashes(): Cirneco dell'Etna
mysqli_real_escape_string(): Cirneco dell'Etna
str_replace(): Cirneco dell'Etna
_GET variable with new value: O'Conner
addslashes(): O\'Conner
mysqli_real_escape_string(): O\'Conner
str_replace(): O\'Conner
The single quote in Cirneco dell'Etna is definitely a single quote, not ` etc. I also tried urlencode() and urldecode() - it replaced spaces with + but did not escape the single quotes. The GETs need single quotes to make user-friendly URLs - usernames and (in this case) breed names for example; Cirneco dell%39Etna is not intuitive. It's not a complex site at all but single quotes crop up a lot as ownership is a major part of the site, so I'd like to work out what's happening!
I have tried switching to PDO but found it beyond me - I'm a novice programmer and my attempt at PDO was mind-boggling to troubleshoot - I can't tell whether errors in PDO are my typos, or a continuation of this same issue.
Many thanks.
EDIT
The select query (which works as expected for _GET variables without single quotes in) is constructed as follows:
$q = "SELECT breed_name, breed_type from b_breed
where breed_name = '" . $_GET['breed'] . "'
LIMIT 1";
$result = mysqli_query($dbc,$q);
if($result->num_rows == 0)
{
}
else
{
$row_breed = mysqli_fetch_array($result, MYSQLI_ASSOC);
{
echo "<h1>" . $row_breed['breed_name'] . " - " . $row_breed['breed_type'] . "</h1>";
}
}
I have tried including addslashes, mysqli_real_escape_string and str_replace (not at the same time) with the $_GET within the query, to no effect. If I echo $q, the single quote is never escaped.
SELECT breed_name, breed_type from b_breed where breed_name = 'Cirneco dell'Etna' LIMIT 1
Oddly, if I switch the double and single quotes so I have:
$q = 'SELECT breed_name, breed_type from b_breed
where breed_name = "' . $_GET['breed'] . '"
LIMIT 1';
SELECT breed_name, breed_type from b_breed where breed_name = "Cirneco dell'Etna" LIMIT 1
It still returns no rows on the page, although the echoed $q will return rows in PHPMyAdmin.
EDIT Solved!
It was changing the ' in the database to an ASCII character. Adding the following converted it back to ', which could then be escaped:
$_GET['breed'] = htmlspecialchars_decode($_GET['breed'], ENT_QUOTES);
You can check what are You getting from GET
try
$string = $_GET['breed'];
for ($i=0;$i<strlen($string);$i++) {
echo '<br>'.$string[$i].' : '.ord($string[$i]);
}

PHP line break with file_put_contents()

I can't seem to figure out why the following code doesn't produce a new line in my text file - neither does using \n etc either - any ideas what could be wrong?
$data = $name . ' | ' . $_POST['comment'] . PHP_EOL;
//write to file
$f = file_put_contents('posts.txt', $data, FILE_APPEND);
Are you viewing the text file in an internet browser by any chance?
If you are, the browser will get rid of the newline characters (unless you're using PRE tags).
Try double quotes: $data = $name . ' | ' . $_POST['comment'] . "\n";
Or: $data = "$name | {$_POST['comment']}\n";
Have you tried \r or \n\r ? Just an idea.

how to define variable from mysql output

I have the following variable which returns my URL as needed. But i need to run str_replace() on it to replace a character before echoing it into my HTML code.
$url = str_replace("%3A", ":", " . nl2br( $row['url']) . ");
As it stands the " . nl2br( $row['url']) . " contains %3A instead of the colon in the URL and for some reason its rendering my links like this
http://www.mydomain.com/http%3A//url.com
I'm not really sure what your question is, but it looks like this is what you want:
$url = urldecode($row['url']);
The %3A is a URL encoded colon (:).

Categories