例如,我有一根绳子:我是个男孩
我想在我的url上显示这一点,例如:index.php?string= in a-boy。
我的节目:
$title = "I am a boy";
$number_wrds = str_word_count($title);
if($number_wrds > 1){
$url = str_replace(' ','-',$title);
}else{
$url = $title;
}如果我有一个字符串:目的地-硅谷
如果我实现相同的逻辑,我的url将是:index.php?string=目标值--硅谷
但我只想显示一个连字符。
我想用连字符代替加号。
url_encode()最终会插入加号。所以这对这里没什么帮助。
现在,如果我使用减号,那么如果实际字符串是目的-硅谷,那么url看起来就像目的地-硅谷而不是目的地-硅谷。
检查这个堆栈溢出问题标题和url。你就会明白我在说什么。
发布于 2014-04-13 10:45:12
使用urlencode()发送字符串和url:
$url = 'http://your.server.com/?string=' . urlencode($string);在您告诉您不需要urlencode的注释中,只需用-字符替换空格即可。
首先,您应该“直接执行”,if条件和str_word_count()只是开销。基本上,您的示例应该如下所示:
$title = "I am a boy";
$url = str_replace(' ','-', $title);就这样。
此外,您还告诉过,如果原始字符串已经包含了-,这将导致问题。我会使用preg_replace()而不是str_replace()来解决这个问题。如下所示:
$string = 'Destination - Silicon Valley';
// replace spaces by hyphen and
// group multiple hyphens into a single one
$string = preg_replace('/[ -]+/', '-', $string);
echo $string; // Destination-Silicon-Valley发布于 2014-04-13 10:44:04
使用preg_replace代替:
$url = preg_replace('/\s+/', '-', $title);\s+的意思是“任何空格字符(\t\r\n\f (空格、制表符、行提要、换行符)”。
发布于 2014-04-13 10:45:31
使用urlencode
<?php
$s = "i am a boy";
echo urlencode($s);
$s = "Destination - Silicon Valley";
echo urlencode($s);
?>返回:
i+am+a+boy
Destination+-+Silicon+Valley和urldecode
<?php
$s = "i+am+a+boy";
echo urldecode($s)."\n";
$s = "Destination+-+Silicon Valley";
echo urldecode($s);
?>返回:
i am a boy
Destination - Silicon Valleyhttps://stackoverflow.com/questions/23041697
复制相似问题