Separate a string in php?

1

I have strings:

$str1 = "nome = stack";
$str1 = "id <5";
$str3 = "senha != over";

How do I pick up the string there in the operator or in space (when there is no space followed by operator it will separate in the operator)? In that case it would look like this:

$str1 = "nome = "; //separou no espaço seguido de operador
$str1c = "stack";
$str2 = "id <"; //separou no operador
$str2c = "5";
$str3 = "senha != "; 
$str3c = "over";

I did not put code, because I do not know how to start.

    
asked by anonymous 23.12.2015 / 21:07

3 answers

2

You can use preg_split along with a regular expression. This method accepts a flag that allows the delimiter to be returned too and included along with the results (I think it needs to be in parentheses, at least that's what I understood in the documentation), so you can concatenate it with the first part to have the division you want:

$arr1 = preg_split("/([^\w\s]+\s*)/", $str1, -1, PREG_SPLIT_DELIM_CAPTURE);
echo $arr1[0] . $arr1[1] . "\n";
echo $arr1[2] . "\n";

Example in ideone . The regular expression used - [^\w\s]+\s* - takes any string that is not letter, digit, or space, optionally followed by a sequence of whitespaces. The result is used to split the string.

[     ]+     Um ou mais caracteres
 ^            que não são:
  \w           uma letra/número
    \s         ou um espaço
        \s*  Seguido de zero ou mais espaços

Note: If your string has two or more operators, preg_split will return an array with more than 3 elements, so plan accordingly.

    
23.12.2015 / 21:37
2

I've also been able to get a more trivial look at the PHP documentation:

$str = "senha != over"; // minha string

$arr = str_split($str); //tranformo em array

$c2 = null; //inicio a variavel caracter2 (c2)

for($i = 0; $i < count($arr); $i ++) //percorro meu array
{
    if($arr[$i] == ">" or $arr[$i] == "<" or $arr[$i] == "=") //olho se é igual aos operadores
    {
        $re = $i; //backup da posição do meu array
        $c = $arr[$i] ; // cópia do caracter do operador

        if($arr[$i+1] == ">" or $arr[$i+1] == "<" or $arr[$i+1] == "=") //olho se no próximo indice tenho mais um operador
            $c2 = $arr[$i+1] ; //copio ele para o c2

        break; // paro o for
    }
}
$arrs = explode($arr[$re], $str); //separa meu array em dois, eliminando meu primeiro operador

if($c2 != null) // se tiver ocorrência de dois operadores
    $arrs[1] = str_replace($c2, "", $arrs[1]); // meu segundo array teré o operador apagado

$str = $arrs[0].$c.$c2; //armazeno senha .!.= (. é a concatenação)
$str2 = $arrs[1]; // armazeno o restante no str2 (restante seria over)

 /*ficaria:
$str = "senha !=";
$str2 = " over";
    
23.12.2015 / 21:37
1

That's all you should do:

/**
 * 
 * @param type $string A string para cortar
 * @return array Um array com 2 elementos
 */
function smart_split($string) {
    # adidione conforme necessidade
    $operators = array('=', '>', '<', '!=', '>=', '<=');    

    foreach ($operators as $operator) {   
        $operator_found = strpos($string, $operator); 

        if ($operator_found !== false) {
            $operator_with_space_found = strpos($string, $operator . ' ');

            if ( $operator_with_space_found  !== false) {               
                return array(
                    substr($string, 0, $operator_with_space_found + 2),
                    substr($string, $operator_with_space_found + 2));
            } else {
                return array(
                    substr($string, 0, $operator_found + 1),
                    substr($string, $operator_found + 1));
            }
        }      
    }

    return array();     
}
    
23.12.2015 / 21:54