Separate a string in php?

Asked

Viewed 966 times

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 the operator it will separate in the operator)? Then I’d be 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 didn’t put code because I don’t know how to start.

  • What would an "operator" be in this case? Would any string be non-alphanumeric and also not white space? My suggestion is to use regex, I will try to assemble an example.

  • It would be < > or =, I’m almost getting here after looking at the PHP documentation, only when I have <= => etc (with two characters) that is not working

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 as well and included along with the results (I think it needs to be in parentheses, at least that’s what I got from the documentation), so you can concatenate ityou 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 the ideone. The regular expression used - [^\w\s]+\s* - takes any string that is not letter, digit or space, optionally followed by a sequence of blank spaces. 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, the preg_split will return an array with more than 3 elements, so plan accordingly.

  • Thank you, it worked perfectly, but I did not understand very well what occurred rs, regex never been my thing. I’ll put it in the code, better than mine with lots of line rs

  • 1

    @Leonardovilarinho Roughly, PHP went around the string until it found a substring that matched that pattern given in the first argument. Found the pattern, he divided the string into 3 - what came before, the married chunk itself, and what came after. The result came in an array.

2

I also managed in a more trivial way looking 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";

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();     
}
  • Those +2 and +1 are like that? Note that some operators have a single character, others have two. Wouldn’t be $operator_with_space_found + strlen($operator) + 1 and $operator_with_space_found + strlen($operator)? Furthermore, good solution, although restricted to a single space after the operator.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.