PHP-从字符串获取子字符串 [英] PHP - Getting a sub-string from a string
问题描述
我有一个字符串
$line = "Name=johnGender=M";
如何制作一个名为$name
的字符串,该字符串的值将存储为john
.
如何提取字符串$ line中包含在=
和G
之间的子字符串.
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.
或者从第一次遇到=
时抓取一个包含4个字符的子字符串(这对我有用).
OR grab a sub-string of 4 characters from the first encounter of =
(this will work for me).
如果$line=array("Name=john&Gender=M",Name=carl&Gender=M",);
该怎么办?我想将它们放入数组$name
中,这样$name=array("john", "carl");
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");
推荐答案
我认为以下内容对您有用.
I guess the following would work for you.
$name = array();
foreach($line as $elem)
array_push($name,substr(explode("=",$elem)[1],0,4));
因此您可以作为$name[0],$name[1],...
最好将输入语法设置为
$line = array("Name=john&Gender=M","Name=raja&Gender=M");
parse_str($line);
因此您可以使用内置功能parse_str()
.
So you can use the built-in function parse_str()
.
现在$Name[0]
包含 john ,而$Name[1]
包含 raja .
这篇关于PHP-从字符串获取子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!