Skip to content Skip to sidebar Skip to footer

Replacing %20 With A Dash

When I echo out the variable below, spaces are represented as %20. $row['title'] So, for instance, if $row['title'] equals 'Portugal Crushes North Korea,' it echoes out as Portuga

Solution 1:

Looks like what you're doing here is encoding the title before it goes into the database!

I would not do it this way. Do not encode data for DB, but encode it as you're looping the results to the page, or even better, add an extra column called slug.

This means the title is Some Clean Title Here and in the slug column you have some-clean-title-here, so then you use $row['slug'].

Then in your link use

<ahref="site_root.tld/post/<?=$row['slug']?>"><?=$row['title'];?></a>

Always escape your data with mysql_real_escape_string and use a function that doesn't just urlencode the slug on db entry, but also creates a sleek, elegant, safely formatted string.

The best form for a slug is a-zA-Z0-9 - _ only.

Solution 2:

Both should do

$string = 'Portugal%20Crushes%20North%20Korea';

echo str_replace('%20', '-', $string);
echo str_replace(' ', '-', rawurldecode($string));

Url Decoding the string before replacement isn't strictly necessary though. It just makes sense in case there is additional encoded characters in the string, e.g.:

echo rawurlencode('Portugal Crushes North Korea (7:0)');
// Portugal%20Crushes%20North%20Korea%20%287%3A0%29

With decoding applied, the space to dash replacement would be

Portugal-Crushes-North-Korea-(7:0)

See the PHP Manual

Solution 3:

Your data is probably url-encoded - use rawurldecode($row['title']) to get it back.

Solution 4:

how could I replace each %20 with a dash?

str_replace('%20', '-', $row['title']);

Post a Comment for "Replacing %20 With A Dash"