PHP - Getting a sub-string from a string

前端 未结 4 1643
野的像风
野的像风 2021-01-15 19:17

I have a string as

$line = \"Name=johnGender=M\";

How to make a string called $name that will have a value stored as joh

相关标签:
4条回答
  • 2021-01-15 19:46

    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.

    0 讨论(0)
  • 2021-01-15 19:58
    <?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

    0 讨论(0)
  • 2021-01-15 20:01

    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

    0 讨论(0)
  • 2021-01-15 20:08

    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

    0 讨论(0)
提交回复
热议问题