There is a line, for example "AK-47 | Red line (Factory New)"

I need to first, depending on what is in brackets, set the desired value to the variable (well, I can do it myself, just need to write everything in brackets to the variable), then remove "(Factory New)".

That is, there was the line "AK-47 | Red Line (Factory New)", and now "AK-47 | Red Line" and in another variable the value of "Factory New".

how to do it?

    4 answers 4

    There are different ways, but it’s necessary to proceed from how different input data variations can be. The first thing that suggests itself is regular expressions, despite the fact that I am far from being a big fan of them:

    preg_match('/(.*)\s\(([^()]+)\)$/', 'AK-47 | Красная линия (Factory New)', $matches); print_r($matches); 

    Or in this way:

     $result = preg_split('/[()]/', 'AK-47 | Красная линия (Factory New)', -1, PREG_SPLIT_NO_EMPTY); print_r($result); 

    You can do without them, provided that the format of the lines will be exactly as you showed in the example. Those. split the string by the opening bracket, if you are sure that it will always be singular:

     $result = array_map(function($a){ return trim($a, ' ()'); }, explode('(', 'AK-47 | Красная линия (Factory New)')); print_r($result); 

    Here is another option:

     $str = 'AK-47 | Красная линия (Factory New)'; $bracket_pos = strpos($str, '('); echo substr($str, 0, $bracket_pos); echo trim(substr($str, $bracket_pos+1), ')'); 

      You can try using regular expressions to highlight the value in brackets.

       preg_match("(.*?)\((.*?)\)", $string, $new_value); 

      He will spread your expression into groups. In the group one will be the inscription to the brackets, in the group two is the inscription in the brackets. Access to them can be obtained as follows:

      • $new_value[1] - 1 group
      • $new_value[2] - 2 group

      For more flexible settings I advise you to read about regular expressions and for the test this resource: https://regex101.com/

      • for ($ i = 0; $ i <count ($ lfdata); $ i ++) {preg_match ("(.?) ((.?))", $ lfdata [$ i] -> name, $ flt); $ lfdata [$ i] -> name = $ flt [1]; echo $ lfdata [$ i] -> name; } - 6o6ep
      • And displays the error Unknown Modifier '(' - 6o6ep
      • Adaptation eaten) add the character \ before the 5 and 10 characters - Yumie
       $str = 'AK-47 | Красная линия (Factory New)'; $first_str = trim(strtok($str, '(')); $second_str = trim(strtok(')')); echo "First: $first_str\n"; echo "Second: $second_str\n"; 

        Another option in the collection of answers:

         $string = "AK-47 | Красная линия (Factory New)"; echo preg_replace('~\s?\([^)]+\)~', '', $string);// AK-47 | Красная линия echo preg_replace('~[\s\S]+[(]|[)]*~', '', $string);// Factory New