Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing %20 with a Dash

Tags:

html

php

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 Portugal%20Crushes%20North%20Korea.

In my source code, how could I replace each %20 with a dash?

Thanks in advance,

John

like image 411
John Avatar asked Jul 04 '26 07:07

John


2 Answers

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

<a href="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.

like image 130
RobertPitt Avatar answered Jul 05 '26 22:07

RobertPitt


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

  • rawurldecode — Decode URL-encoded strings
like image 30
Gordon Avatar answered Jul 05 '26 20:07

Gordon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!