我遇到这种情况,我可以使用这样的字符串:
"Project\\V1\\Rest\\Car\\Controller"
"Project\\V1\\Rest\\Boat\\Controller"
"Project\\Action\\Truck"
"Project\\V1\\Rest\\Helicopter\\Controller"
"Parental\\Boat\\Action"
以防该字符串遵循以下模式:
"Project\\V1\\Rest\\THE_DESIRED_WORD\\Controller"
我想得到THE_DESIRED_WORD。
这就是为什么我在用正则表达式思考。
答案 0 :(得分:1)
要使用正则表达式,您需要两次转义斜杠:一次用于PHP字符串,一次用于正则表达式
试试这个:
$tab = array(
"Project\\V1\\Rest\\Car\\Controller",
"Project\\V1\\Rest\\Boat\\Controller",
"Project\\V1\\Rest\\Helicopter\\Controller",
"Project\\V1\\Rest\\Water\\Controller",
);
foreach ($tab as $s) {
preg_match("!\\\\([^\\\\]*)\\\\Controller!U", $s, $result);
var_dump($result);
}
答案 1 :(得分:0)
<?php
$str='"Project\\V1\\Rest\\Car\\Controller"
"Project\\V1\\Rest\\Boat\\Controller"
"Project\\V1\\Rest\\Helicopter\\Controller"
"Project\\V1\\Rest\\Water\\Controller"';
$line=explode(PHP_EOL,$str);
//print_r($line);
foreach ($line as $l){
$x=explode("\\",$l);
if($x[0]=='Project' && $x[1]=='V1' && $x[2]=='Rest' && $x[4]=='Controller' ){
echo $x[3];
}
}
答案 2 :(得分:0)
爆炸使用\\
分隔符完成工作:
<?php
$str1 = "Project\\V1\\Rest\\Car\\Controller";
$str2 = "Project\\V1\\Rest\\Boat\\Controller";
$str3 = "Project\\V1\\Rest\\Helicopter\\Controller";
$str4 = "Project\\V1\\Rest\\Water\\Controller";
$arr1 = explode( "\\",$str1 );
$arr2 = explode( "\\",$str2 );
$arr3 = explode( "\\",$str3 );
$arr4 = explode( "\\",$str4 );
echo $arr1[ 3 ] . ", " .
$arr2[ 3 ] . ", " .
$arr3[ 3 ] . ", " .
$arr4[ 3 ];
?>
将显示:
Car, Boat, Helicopter, Water