【问题标题】:Searching for name in a string PHP在字符串 PHP 中搜索名称
【发布时间】:2014-04-09 10:42:35
【问题描述】:

我在 php 中有一个字符串,我试图从中获取名称。

字符串输出是“| name=thomas | country=usa”等

我希望能够将名称“thomas”放入 php 变量中。

注意:数据是动态的,所以我试图找到一种无需硬编码 thomas 的搜索方式。

这是我的代码:

    $people= ($_GET['people']);

preg_match_all('/name="([^"]+)"/mi', $people, $matches);

var_dump ($matches[1]);

我在 php 中收到一个数组到字符串的转换错误。

【问题讨论】:

  • 这是产生问题字符串的代码吗?在那种情况下,你是如何让$matches[1] 输出一个字符串的?它应该输出一个数组
  • 为什么在模式中使用双引号?另外,请告诉我们您的 $_GET['people'] 到底长什么样?总是这样吗? "| name=thomas | country=usa "

标签: php string search


【解决方案1】:

使用这个正则表达式

<?php
$str='| name=thomas | country=usa ';
preg_match_all('/=(.*?) /', $str, $matches);
print_r($matches[1][0]);  //"prints" thomas

【讨论】:

  • 谢谢,我认为这会搜索 '=' 以及之后的任何内容,直到空格? :P
【解决方案2】:
function yourSearch($haystack) {
    $string= 'Enter value to search for';
    return(strpos($mystack, $string)); // or stripos() if you want case-insensitive searching.
}

$matches = array_filter($your_array, 'yourSearch');

【讨论】:

    猜你喜欢
    • 2021-03-26
    • 2012-07-23
    • 1970-01-01
    • 2021-10-06
    • 2017-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多