str_replace php获取链接


str_replace php for links

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

我的当前代码

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

我正在寻找它为任何字符,如$,#,&不仅仅是空间。

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

这将创建一个变量$replace,用str_replace'替换带有连字符的数组中的任何内容

这是我用来创建slugs 的

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

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

首先创建一个要替换的字符数组:

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

然后在str_replace中给它一个数组名称:

$originalString = '<a href="http://www.somewhere.co.uk">My Link</a>';
$newString = str_replace($replace, "", $originalString);

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

您可以向str_replace函数发送array,如下所示:

$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>

来源于askingbox作者:

$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>