简体   繁体   English

PHP正则表达式拆分

[英]PHP regular expression split

I will make this quick and simple 我将使这个过程变得简单快捷

I have a query and I want to split it so that it returns an array with words after the : symbol. 我有一个查询,我想对它进行拆分,以便它在:符号后返回一个包含单词的数组。 This is what I have so far and it does as expected but returns the whole string before the matched needle. 这是我到目前为止所能完成的,并且按预期执行,但是在匹配的针之前返回了整个字符串。 I just want the array to contain words after the : symbol. 我只希望数组在:符号后包含单词。

<?php  $arr = preg_split('/[:]/', $query, 0); 

   print_r($arr);

 ?>

This returns 这返回

    Array
(
    [0] => SELECT user_name FROM test WHERE user_name = 
    [1] => user_name
)

using this query 使用此查询

"SELECT user_name FROM test WHERE user_name = :user_name" “从测试WHERE用户名=:用户名中选择用户名”

thanks for any help 谢谢你的帮助

Try this: 尝试这个:

preg_match_all("/:(\w+)/", $string, $matches);

By doing this, all your elements that are after a : will be in $matches[1] sub-array. 这样,位于:之后的所有元素都将位于$ matches [1]子数组中。 I'm assuming you want to handle SQL statements with multiple named parameters. 我假设您要处理带有多个命名参数的SQL语句。 So for example: 因此,例如:

SELECT user_name FROM test WHERE user_name = :user_name and last_name = :last_name

Will result in $matches being: 将导致$ matches为:

array(2) {
  [0]=>
  array(2) {
    [0]=>
    string(10) ":user_name"
    [1]=>
    string(10) ":last_name"
  }
  [1]=>
  array(2) {
    [0]=>
    string(9) "user_name"
    [1]=>
    string(9) "last_name"
  }
}

I edited your question so it's better for others to see result.But answer: preg_split returns an array, and what you're seeking is an element of array: 我编辑了您的问题,以便其他人更好地查看结果。但是答案: preg_split返回一个数组,而您要查找的是数组的元素:

<?php  $arr = preg_split('/[:]/', $query, 0); 

   print($arr[1]);

 ?>

this returns user_name as you wanted. 这将根据需要返回user_name

You might want to use, preg_match() for this 您可能要为此使用preg_match()

$query = "SELECT user_name FROM test WHERE user_name = :user_name";
preg_match('/:(\w+)/', $query, $matches);
echo $matches[1]; //gives your user_name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM