Php 剥离变量供 url 使用

Php strip variable for url use

所以基本上我有一个 php 变量,我想将其添加到 url 中。问题是,如果变量中包含奇怪的字符,url 将不起作用。

我的例子:

URL: http://localhost/myapp/products/$variable

变量可以是这样的:

$variable = 'books';               //books
$variable = 'art and design';      //art_and_design
$variable = '< 220g de CO2/Kg';    //_220g_de_CO2 
$variable = '< 220g /de CO2/Kg';    //_220g_

http://localhost/myapp/products/books
http://localhost/myapp/products/art_and_design
http://localhost/myapp/products/_220g_de_CO2
http://localhost/myapp/products/_220g_

我想剥离变量以使其看起来像注释中的值,这意味着空格应替换为 _ 并同时删除与 url (<要么 /)。

如您所见,我删除了第一个字符和最后 3 个字符,只保留了好的部分,因为我将它用于数据库中的搜索(LIKE 运算符),如果我将它不起作用仅删除 / 并保留 Kg

我需要一个函数来为我做这件事,目前看起来是这样的:

function stripVar($variable){
    return str_replace(' ', '_', $variable);
}

但我不知道如何处理另一部分。谢谢。

您可以只使用 url_encode()http://php.net/manual/en/function.urlencode.php 然后 url_decode() 得到真正的变量。然后你就可以使用它了。

除了 url_encode() 之外,您还可以使用以下具有更多 "pretty" 输出的函数:

function prettyURL($variable)
{
return  preg_replace('/^-+|-+$/', '', strtolower(preg_replace('/[^a-zA-Z0-9]+/', '_', $variable)));
}   

对于您的变量,它产生了以下输出:

Variable 1: books
Variable 2: art_and_design
Variable 3: _220g_de_co2_kg

更新,删除了 strtolower:

function prettyURL($variable)
{
    return  preg_replace('/^-+|-+$/', '', preg_replace('/[^a-zA-Z0-9]+/', '_', $variable));
} 

输出:

Variable 1: books
Variable 2: art_and_design
Variable 3: _220g_de_CO2_Kg

Making strings "URL safe"

您可以使用数组(第一个参数)删除您想要的内容:

$whatRemove = array(' ', '<', 'Kg'); // add more if you need.
str_replace($whatRemove,'', $variable);

这样可以吗?

$arr = array('books', 'art and design', '< 220g de CO2/Kg', '< 220g/ de CO2/Kg'); 
foreach($arr as $variable) {
    echo "$variable -> ";
    $variable = preg_replace('/\s+/', '_', $variable);
    $variable = preg_replace('~(?:^[^</]*[</]+|[</]+.*$)~', '', $variable);
    echo $variable,"\n";
}

输出:

books -> books
art and design -> art_and_design
< 220g de CO2/Kg -> _220g_de_CO2
< 220g/ de CO2/Kg -> _220g