繁体   English   中英

用PHP转换特殊字符

[英]Converting Special Characters with PHP

我试图将一个标准的wordpress标题变成一个段,使所有字符变为小写,用破折号替换空格,并删除标题中的所有“&”符号。

因此,以该标题为例:“ Identity&Wayfinding

这是我的PHP:

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

这使我的标题变成“ identity-#038;-寻路

小写转换有效,但不替换“&”无效。 它将“&”转换为HTML特殊字符。 任何想法我都可以简单地用空格替换“&”,然后在其后删除破折号,以便最终标题为: “ identity-wayfinding”

如果您想要一个子弹,有很多实用程序可以为您完成,但是htmlentities或urlencode都不正确。 Doctrine 1.2包含一个带有一系列静态函数的urlizer类,其中包括urilize ,它将以更可靠的方式(正确处理UTF-8和不加重音等)完成您所需的行为。

可以在这里找到

如果您想要一些不那么健壮但简单得多的东西:

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;
}

这将除去非字母数字字符(但也带重音字符),并将空格,+号和连字符分隔为连字符。

首先删除“”(空格),然后删除“-”,然后将&替换为破折号,以使用str_replace

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

echo $title; // returns: identity-wayfinding

例子@ viper7

您可能正在谈论,请参阅以下内容:

使用此代码:

 <?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"');
?>

现场例子

当然,如果要在Wordpress中使用此功能,则只需要使用此功能:

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

其中,如果$title输出为空,则$title是输入字符串,而$fallback_title是默认值。 在此处阅读更多内容: Wordpress函数参考/清除标题

这是我使用的功能。

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));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM