我有一个字符串,可以收集两条信息。 斜杠之前的所有内容都是搜索变量,斜杠之后的所有内容都是页码。
假设以下情况:
$search = "classic rock/8"
应该是$searchvalue[0]='经典$searchvalue[1]='摇滚' $searchvalue[x]= 等等...然后 $page=8
我尝试了几种方法,最后一种方法是通过先删除斜杠后的所有内容来执行三遍。
$search=substr($search, 0, strpos($search, '/'));
然后将$search值分隔到数组中。然后返回(第三次!)并通过删除斜杠之前的所有内容来获取页面变量。
我知道这是非常低效的。 有没有办法一次性完成这些操作?
提前感谢!
你可以把这个字符串分解两次,得到相同的结果!
$res = explode("/", $search);
$page = $res[1]; //This is the page
$searchValues = explode(" ", $res[0]); //These are the results
您可以使用
strrpos
:
$search = 'classic rock/8';
$page = substr($search, strrpos($search, '/')+1); // 8
为了响应一次性获得它,您可以使用 preg 匹配所有功能或
您可以使用预处理拆分功能。
无论哪种方式都有其缺点,但爆炸和 strrpos 或其他任何东西也是如此。
很多人没有意识到他们可以更详细地
使用预分精确地切开一根绳子。这可以通过详细定义拆分以包括捕获来完成。这种方式有点不同,但如果你学会了如何做到这一点,它的力量就会很大。
正则表达式:
# ([^'s'/]+)(?:'s+|$)|'/+'s*('d+)['s'/]*$|'/.*$
# Delim-1
( [^'s'/]+ ) # (1), A group of not whitespace nor forward slash
(?: 's+ | $ ) # folowed by whitespace or EOL
# Delim-2
| '/+ 's* # Forward slashes folowed by whitespaces
( 'd+ ) # (2), folowed by a group of digits
['s'/]* $ # followed by whitespaces or slashes until EOL
# Delim-3
| '/ .* $ # Forward slash folowed by anything until EOL
PHP代码:
<?php
$keywords = preg_split
(
"/([^'s'/]+)(?:'s+|$)|'/+'s*('d+)['s'/]*$|'/.*$/",
"classic rock/8",
-1,
PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE
);
print_r($keywords);
?>
Result:
Array
(
[0] => classic
[1] => rock
[2] => 8
)