str_replace php的链接

时间:2013-08-09 14:05:10

标签: php string replace

想要替换谷歌索引我的链接没有空格,逗号和其他字符

我的代码

<a href="report-<?php echo str_replace(" ", "-", $db['Subject'])?>-<?=$db['id']?>" class="read-more-button">Read More</a>

我希望为任何字符制作它,例如$,#,&amp;,! ;不仅仅是空间。

5 个答案:

答案 0 :(得分:0)

这是我用来创建slugs的东西

strtolower(preg_replace('/[\s-]+/', '-', preg_replace('/[^A-Za-z0-9-]+/', '-', preg_replace('/[&]/', 'and', preg_replace('/[\']/', '', trim($string))))));

答案 1 :(得分:0)

str_replace函数允许您使用数组进行替换。像这样:

首先创建一个要替换的角色数组:

$replace = array(" ", "-", "_", "#", "+", "*");

然后在str_replace中为它提供数组名称:

$originalString = '<a href="http://www.somewhere.co.uk">My Link</a>';

$newString = str_replace($replace, "", $originalString);

$ newString将删除$ replace数组中的每个项目。

答案 2 :(得分:0)

您可以将array发送到str_replace功能,如下所示:

$strip = array('%','$','#','&','!'); 
<a href="report-<?=str_replace($strip, '-', $db['Subject'])?>-<?=$db['id']?>" class="read-more-button">Read More</a>

但是,要创建URL我使用:

<?php
    function stripChars($str)
    {
        $bads    =    array(".","+"," ","#","?","!","&" ,"%",":","–","/","\\","'","\"","”","“",",","£","’");
        $goods   =    array("","-","-","-","" ,"" ,"and","" ,"" ,"" ,"","","","","","","","","","");
        $str    =    str_replace($bads,$goods,$str);
        return strtolower($str);
    }
?>
    <a href="<?=stripChars('report ' . $db['Subject'] . ' ' . $db['id'])?>" class="read-more-button">Read More</a>

答案 3 :(得分:0)

<?php
$replace=str_replace(array(" ","\$","#","&","!",";"),'-',$db['Subject']);
echo "<a href='report-{$replace}-{$db['id']}' class='read-more-button'>Read More</a>";
?>

这会创建一个变量$ replace,并使用连字符

对数组中的任何内容进行str_replace

答案 4 :(得分:0)

来自askbox作者的信用:

$f = 'fi?le.txt';

$f = str_replace(array('$', '#',' &', '!', '\\','/',':','*','?','"','<','>','|'),' ',$f);

echo $f; // 'fi le.txt'

使用:

function make_safe($str){
return  str_replace(array('$', '#',' &', '!', '\\','/',':','*','?','"','<','>','|'),' ',$str);
}

<a href="report-<?php echo make_safe($db['Subject'])?>-<?=$db['id']?>" class="read-more-button">Read More</a>