JCHASE11
JCHASE11

Reputation: 3941

Converting Special Characters with PHP

I am trying to turn a standard wordpress title into a slug, that makes all characters lowercase, replaces spaces with dashes, and removes all "&" symbols that are in the titles.

So lets use this title as an example: "Identity & Wayfinding"

Here is my PHP:

<?php 
$title = get_the_title(); 
$lower = strtolower($title);
$noDash = str_replace(' ', '-', $lower);
$noAnd = str_replace('&', '', $noDash);
echo $noAnd;
?>

This turns my title into "identity-#038;-wayfinding"

The lowercase conversion worked, but the replacing of the"&" with nothing isnot working . It is converting the "&" into an HTML special character. Any idea how I can simply replace the "&" with a blank, but also REMOVE the dash after that so the final title would be: "identity-wayfinding"?

Upvotes: 0

Views: 2418

Answers (5)

DavChana
DavChana

Reputation: 1966

Use this code:

 <?php
function create_slug($string){
$slug=preg_replace('/[^A-Za-z0-9-]+/', '-', $string);
$slug=ltrim($slug, "-");
$slug=rtrim($slug, "-");
return strtolower($slug);
}
echo create_slug('does this thing work or not');
//returns 'does-this-thing-work-or-not'

echo "<br />";
echo create_slug('"Identity & Wayfinding"');
?>

Live Example

Of course if you want to use this function in Wordpress, you just need to use this:

<?php sanitize_title( $title, $fallback_title ) ?>

Where, $title is the input string & $fallback_title is the default value, if $title comes out empty. Read more here: Wordpress Function Reference/Sanitize Title

Upvotes: 0

David B&#233;langer
David B&#233;langer

Reputation: 7438

Here's the function I use.

function text_as_url($str='', $separator = 'dash', $lowercase = false){
    if ($separator == 'dash'){
        $search     = '_';
        $replace    = '-';
    } else {
        $search     = '-';
        $replace    = '_';
    }

    $trans = array(
                    '\/'                    => '-',
                    '&\#\d+?;'              => '-',
                    '&\S+?;'                => '-',
                    '\s+'                   => $replace,
                    '[^a-z0-9\-\._]'        => '', // accents
                    $replace.'+'            => $replace,
                    $replace.'$'            => $replace,
                    '^'.$replace            => $replace,
                    '\.+$'                  => '-'
                );

    $str = strip_tags($str);

    foreach ($trans as $key => $val){
        $str = preg_replace("#".$key."#i", $val, $str);
    }

    if($lowercase === true){
        $str = strtolower($str);
    }

    return trim(stripslashes($str));
}

Upvotes: 0

user529649
user529649

Reputation:

Use the str_replace by first removing the " "(space), then "-" and then replacing the & with dash.

$title = "Identity & Wayfinding";
$title = strtolower(str_replace(array(" ","-","&"),array("","","-"),$title));

echo $title; // returns: identity-wayfinding

Example@viper7.

Upvotes: 0

complex857
complex857

Reputation: 20753

You are probably talking about slugs, see these:

Upvotes: 0

Lusitanian
Lusitanian

Reputation: 11132

If you want a slug, there are plenty of utilities which will do it for you, but neither htmlentities or urlencode is correct. Doctrine 1.2 included a urlizer class with a set of static functions including urilize which will accomplish the behavior you desire in a more robust manner (handles UTF-8 and unaccenting correctly, etc.)

It can be found here

If you want something less robust but far simpler:

function slugify($sluggable)
{
    $sluggable = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $sluggable);
    $sluggable = trim($sluggable, '-');
    if( function_exists('mb_strtolower') ) { 
        $sluggable = mb_strtolower( $sluggable );
    } else { 
        $sluggable = strtolower( $sluggable );
    }
    $sluggable = preg_replace("/[\/_|+ -]+/", '-', $sluggable);

    return $sluggable;
}

That'll strip non-alphanumeric characters (but also accented characters) and make spaces, + signs, and hyphens into hyphens.

Upvotes: 3

Related Questions