给定字符串后的PHP拆分字符串

时间:2012-11-05 14:37:25

标签: php

我知道标题有点令人困惑,但这是一个例子:

字符串:SELECT * FROM tbl_clients ORDER BY updatedOn LIMIT 0,50

我想要的是在 FROM之后取出所有并将其放入新的字符串中。

所以我的结果字符串看起来像是:tbl_clients ORDER BY updatedOn LIMIT 0,50

有没有办法做他的?

5 个答案:

答案 0 :(得分:3)

好吧,你可以这样使用explode

$string="SELECT * FROM tbl_clients ORDER BY updatedOn LIMIT 0,50";
$split=explode("FROM", $string, 2); 
//Restricts the split to 2 elements, i.e., everything after first occurrence goes in the second element

$result=$split[1];

答案 1 :(得分:2)

您可以尝试类似

的内容
$mystring = "SELECT * FROM tbl_clients ORDER BY updatedOn LIMIT 0,50";
$spliter = "FROM ";
$splitstring = explode($spliter, $mystring);

$result = $splitstring[1];

答案 2 :(得分:2)

有很多方法可以做到这一点(stripos-substr,explode)等,但这里有 preg_split()方式:

$sql = 
    "SELECT * FROM tbl_clients ORDER BY updatedOn " .
    "WHERE `from`='something' LIMIT 0,50";
$r = preg_split( "/FROM /i", $sql );
print_r( $r );

给你$ r [1]玩:

Array
(
    [0] => SELECT * 
    [1] => tbl_clients ORDER BY updatedOn WHERE `from`='something' LIMIT 0,50
)

在某些情况下,preg_split可能非常方便,比如解析整个语句:

$r = preg_split( "/(SELECT)|(FROM)|(ORDER BY)|(WHERE)|(LIMIT)/i", $sql );

在一个声明中给你一个更简洁的细分:

Array
(
    [0] => 
    [1] =>  * 
    [2] =>  tbl_clients 
    [3] =>  updatedOn 
    [4] =>  field='something' 
    [5] =>  0,50
)

答案 3 :(得分:1)

split FROM上的字符串为您提供数组,然后访问数组的第1个元素。

$query_array = preg_split("/FROM /i", "SELECT a,b,d FROM tableA WHERE b=2", 1);
$table_and_clause = $query_array[1];  // "tableA WHERE b=2"...

答案 4 :(得分:1)

对于无法阅读strpos()substr()

的相应手册页的用户
$string = 'SELECT * FROM tbl_clients ORDER BY updatedOn LIMIT 0,50';
$pos = strpos($string, ' FROM ');
$substring = substr($string, $pos + strlen(' FROM '));