tcd
tcd

Reputation: 1605

PHP replace hashtag with url friendly text

I am working with a PHP version the Pinterest Pin It button and I'm running into a problem with the "description" portion of the url...

I'm using php to generate the url:

$pinurl = 'http://foo.com';
$pinmedia = 'http://foo.com/picture.jpg';
$pindesc = 'my description with #hashtag';

$pin = 'http://pinterest.com/pin/create/button/?url='.$pinurl.'&media='.$pinmedia.'&description='.$pindesc.'';

echo '<a href="'.$pin.'" class="pin-it-button" count-layout="none" target="_blank">Pin It!</a>';

The problem I run into is when my $pindesc variable has a hashtag in it or only a hashtag, Pinterest doesn't read it from the url because it looks like:

http://pinterest.com/pin/create/button/?url=http://foo.com&media=http://foo.com/foo.jpg&description=#foo

So obviously the #foo isn't being read as a description...

I was wondering if there's some sort of work around or if I could use an "if" statement to run through my $pindesc variable to check for and replace hashtags with "%23" which is "url friendly"

Thanks!

Upvotes: 0

Views: 2438

Answers (2)

zamnuts
zamnuts

Reputation: 9592

Use rawurlencode:

$pin = 'http://pinterest.com/pin/create/button/?url='.rawurlencode($pinurl).'&media='.rawurlencode$pinmedia).'&description='.rawurlencode($pindesc).'';

This will URL encode all characters except for -_.~ (RFC 3986)

Upvotes: 3

John C
John C

Reputation: 8415

You can use urlencode to convert any tricky characters in your script:

$pindesc = urlencode('my description with #hashtag');

Upvotes: 3

Related Questions