Oriam
Oriam

Reputation: 641

How to get a portion of a string with a regular expression

I have this situation where I can have strings like this:

"Project\\V1\\Rest\\Car\\Controller"
"Project\\V1\\Rest\\Boat\\Controller"
"Project\\Action\\Truck"
"Project\\V1\\Rest\\Helicopter\\Controller"
"Parental\\Boat\\Action"

Just in case the string follow the pattern:

"Project\\V1\\Rest\\THE_DESIRED_WORD\\Controller"

I want to get THE_DESIRED_WORD.

That's why I'm thinking in a regular expression.

Upvotes: 0

Views: 37

Answers (3)

user557846
user557846

Reputation:

<?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];
   }
}

Upvotes: 0

Explode does the job using \\ separator :

<?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 ];

?>

Will display:

Car, Boat, Helicopter, Water

Upvotes: 0

mmm
mmm

Reputation: 1149

to use a regular expression, you need to escape the slash twice : once for the PHP string and once for the regex

try this :

$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);
}

Upvotes: 1

Related Questions