用PHP替换url字符串

时间:2014-04-13 10:40:26

标签: php url-rewriting

我有一个字符串例如:我是个男孩

我想以这种方式在我的网址上显示:index.php?string = I-am-a-boy

我的节目:

            $title = "I am a boy";

            $number_wrds = str_word_count($title);
            if($number_wrds > 1){
            $url = str_replace(' ','-',$title);
            }else{
            $url = $title;
            }

如果我有一个字符串怎么办:目的地 - 硅谷

如果我实现相同的逻辑,我的网址将是:index.php?string = Destination --- Silicon-Valley

但我想只显示一个连字符。

我想显示连字符而不是加号..

url_encode()最终将插入加符号..所以它在这里没有帮助。

现在,如果我使用减号,那么如果实际的字符串是目的地 - 硅谷,那么网址就会如此 目的地 - 硅谷而不是 目的地---硅谷

检查此stackoverflow问题标题和网址。你会知道我在说什么。

Check this

4 个答案:

答案 0 :(得分:2)

使用urlencode()发送字符串以及网址:

$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

答案 1 :(得分:0)

改为使用preg_replace

$url = preg_replace('/\s+/', '-', $title);

\s+表示"任何空白字符(\t\r\n\f(空格,制表符,换行符,换行符))。

答案 2 :(得分:0)

使用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 Valley

答案 3 :(得分:0)

只需使用urlencode()urldecode()即可。它用于在URL中使用GET发送数据。