Search for text between " ("and") " in a PHP string
In PHP, I need to use a regular string to pull out all the text elements enclosed in parentheses for their further processing, for example, the string:
(Ширина)*(Длина)+(Пользовательская константа)
I need this to eventually replace them with variable names in Js and get a string like:
Width*Height+User_constant
Data for translation-I will specify in the array, but I do not know how to make the replacement itself. If you can, then help at least with the regular search (search for this very text between the brackets) and output the result to the array
2 answers
remove all text elements enclosed in parentheses from the string
Dak preg_match_all() use:
$str = '(Ширина)*(Длина)+(Пользовательская константа)';
$pattern = '~\(\K.+?(?=\))~';
preg_match_all($pattern, $str, $arr);
var_dump($arr);
Result:
array (size=1)
0 =>
array (size=3)
0 => string 'Ширина' (length=12)
1 => string 'Длина' (length=10)
2 => string 'Пользовательская константа' (length=51)
I decided to use the " | " separator in this case, since parentheses can be used multi-level like ((x)+(y))/(z), now I have edited the regular expression
~\(\K.+?(?=\))~
and brought him to the view:
~\|\K.+?(?=\|)~
Now when you request:
|Door width / / |Log price eb|-|Door length|
I get:
[0]=> array(5){
[0]=> string(23) "Ширина двери"
[1]=> string(1) "/"
[2]=> string(26) "Цена бревна ев"
[3]=> string(1) "-"
[4]=> string(21) "Длина двери" }
}```