Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何$\u从字符串中获取值_Php - Fatal编程技术网

Php 如何$\u从字符串中获取值

Php 如何$\u从字符串中获取值,php,Php,这是我的绳子 component/content/article?id=9 如何从中动态获得9 我想在字符串上做这件事,而不是在url上,当有更多的paremateres时,就像在url中一样。 我想做同样的事情,比如$\u GET,但是是字符串 改写问题(由Ayesh K): 我有一个包含URL路径和查询字符串的字符串。我想将查询字符串解析为一组键和值,就像它是当前页面的查询字符串一样,这样我就可以从$\u get中获取它们 例如,我有以下字符串: component/content/art

这是我的绳子

component/content/article?id=9
如何从中动态获得9

我想在字符串上做这件事,而不是在url上,当有更多的paremateres时,就像在url中一样。 我想做同样的事情,比如$\u GET,但是是字符串

改写问题(由Ayesh K):

我有一个包含URL路径和查询字符串的字符串。我想将查询字符串解析为一组键和值,就像它是当前页面的查询字符串一样,这样我就可以从
$\u get
中获取它们

例如,我有以下字符串:

component/content/article?id=9

现在我想从数组中获取
id
值(
9
)。如何解析这样的字符串以分离查询字符串并将其转换为数组?

更新:我看到您更新了代码

这是解析URL字符串的一种更健壮的方法:

$string = 'component/content/article?q=1&item[]=345&item[]=522';

// parse the url into its components
$url_parts = parse_url($string);

// parse the query components to get the variables
parse_str($url_parts['query'], $get_vars);

echo $get_vars['q'];
echo $get_vars['item'][0];

这里的一些答案没有使用为此而构建的特定工具

您可以使用以下命令来解析URL或路径字符串,并获得所需的值,就像它在$\u get中一样

<?php
  $str = 'component/content/article?id=9';
  $query = parse_url($str, PHP_URL_QUERY); // Get the string part after the "?"
  parse_str($query, $params); // Parse the string. This is the SAME mechanism how php uses to parse $_GET.
  print $params['id'];
?>


演示:

不工作,正在返回字符。很遗憾,这不起作用。此外,如果URL包含数组格式(
example.com/?q=1&item[]=345&item[]=522
),则此操作将失败。是否忘记添加“=”分解,是否真正修复?请试着自己搜索一下。
<?php
  $str = 'component/content/article?id=9';
  $query = parse_url($str, PHP_URL_QUERY); // Get the string part after the "?"
  parse_str($query, $params); // Parse the string. This is the SAME mechanism how php uses to parse $_GET.
  print $params['id'];
?>