检查 URL 是否包含字符串,然后使用 url 字符串创建变量
Check if URL contains string then create variables with url strings
我需要检查 URL 是否包含术语:"cidades"。
例如:
http://localhost/site/cidades/sp/sorocaba
所以,如果是肯定的,那么我需要创建两个或三个变量,其余内容不带“/”,在这种情况下:
$var1 = "sp";
$var2 = "sorocaba";
这些变量将是页面开头的cookie值,然后,某些部分将使用这些值作为wp-query来过滤。
这应该适合你:
这里我用preg_match()
if the search word is in the url $str
between two slashes. If yes I get the substr()
from the url after the search word and explode()
it into an array with a slash as delimiter. Then you can simply loop through the array an create the variables with complex (curly) syntax检查一下。
<?php
$str = "http://localhost/site/cidades/sp/sorocaba";
$search = "cidades";
if(preg_match("~/$search/~", $str, $m, PREG_OFFSET_CAPTURE)) {
$arr = explode("/", substr($str, $m[0][1]+strlen($m[0][0])));
foreach($arr as $k => $v)
${"var" . ($k+1)} = $v;
}
echo $var1 . "<br>";
echo $var2;
?>
输出:
sp
sorocaba
这里有两个函数可以为您完成:
function afterLast($haystack, $needle) {
return substr($haystack, strrpos($haystack, $needle)+strlen($needle));
}
和PHP的原生explode
。
首先调用 afterLast
,传递 /cidades/
字符串(如果您不需要斜线,则只传递 cidades
)。然后在 /
上获取结果和 explode
以获得结果数组。
看起来像:
$remaining_string = afterLast('/cidades/', $url);
$items = explode('/', $remaining_string)
请注意,如果您 不 在 afterLast
调用中包含 /
标记,则您的第一个元素在 explode
数组中将是空的。
我认为这个解决方案更好,因为生成的数组将支持任意数量的值,而不仅仅是两个。
我需要检查 URL 是否包含术语:"cidades"。
例如:
http://localhost/site/cidades/sp/sorocaba
所以,如果是肯定的,那么我需要创建两个或三个变量,其余内容不带“/”,在这种情况下:
$var1 = "sp";
$var2 = "sorocaba";
这些变量将是页面开头的cookie值,然后,某些部分将使用这些值作为wp-query来过滤。
这应该适合你:
这里我用preg_match()
if the search word is in the url $str
between two slashes. If yes I get the substr()
from the url after the search word and explode()
it into an array with a slash as delimiter. Then you can simply loop through the array an create the variables with complex (curly) syntax检查一下。
<?php
$str = "http://localhost/site/cidades/sp/sorocaba";
$search = "cidades";
if(preg_match("~/$search/~", $str, $m, PREG_OFFSET_CAPTURE)) {
$arr = explode("/", substr($str, $m[0][1]+strlen($m[0][0])));
foreach($arr as $k => $v)
${"var" . ($k+1)} = $v;
}
echo $var1 . "<br>";
echo $var2;
?>
输出:
sp
sorocaba
这里有两个函数可以为您完成:
function afterLast($haystack, $needle) {
return substr($haystack, strrpos($haystack, $needle)+strlen($needle));
}
和PHP的原生explode
。
首先调用 afterLast
,传递 /cidades/
字符串(如果您不需要斜线,则只传递 cidades
)。然后在 /
上获取结果和 explode
以获得结果数组。
看起来像:
$remaining_string = afterLast('/cidades/', $url);
$items = explode('/', $remaining_string)
请注意,如果您 不 在 afterLast
调用中包含 /
标记,则您的第一个元素在 explode
数组中将是空的。
我认为这个解决方案更好,因为生成的数组将支持任意数量的值,而不仅仅是两个。