PHP - Getting a sub-string from a string

2020-03-31 02:43发布

问题:

I have a string as

$line = "Name=johnGender=M";

How to make a string called $name that will have a value stored as john. How to extract a sub-string which is enclosed between = and G in the string $line.

OR grab a sub-string of 4 characters from the first encounter of = (this will work for me).

What if $line=array("Name=john&Gender=M",Name=carl&Gender=M",); And I wanted to put them in an array $name So that $name=array("john", "carl");

回答1:

I guess the following would work for you.

$name = array();
foreach($line as $elem)
    array_push($name,substr(explode("=",$elem)[1],0,4));

So you can access it as $name[0],$name[1],...

Better try to have the input syntax as

$line = array("Name=john&Gender=M","Name=raja&Gender=M");
parse_str($line);

So you can use the built-in function parse_str().

Now $Name[0] contains john and $Name[1] contains raja.



回答2:

Suppose we dont know the length of the name. Say, $line = "Name=SaifUrRehmanGender=M";

Use strpos() to get the index of "Gender"

The strpos() function finds the position of the first occurrence of a string inside another string.

For your case: $name = substr($line,5,strpos($line,"Gender")-5); will do :)

Output: SaifUrRehman



回答3:

Try this :

function strinbetween($inputstring, $start, $end){
    $inputstring = " ".$inputstring;
    $ini = strpos($inputstring,$start);
    if ($ini == 0) {
        return "";
    }
    $ini += strlen($start);
    $len = strpos($inputstring,$end,$ini) - $ini;
    return substr($inputstring,$ini,$len);
}

Call the above function and pass the string, starting string and ending string

$line = "Name=johnGender=M";
$parsed = strinbetween($line,'=','G');
echo $parsed;

So here it will return john



回答4:

<?php

$line = "Name=johnGender=M";
//explode the string by '='
$info = explode('=', $line);
//then you have in $info[1] this string: johnGender
// and you get the first 4 characters in $name
$name = substr($info[1], 0, 4);

echo $name;

?>

Output:

john

<?php

$line = array("Name=john&Gender=M","Name=carl&Gender=M");

$array = array();

for($i = 0; $i < count($line); $i++) {
  $info = explode('=', $line[$i]);
  $name = explode('&', $info[1]);
  $array[] = $name[0];
}   

foreach($array as $name) {
    echo $name . "<br>\n";
}   

?>

Output:

john

carl