Why prints the entire line, if I indicated that only the first pocket is needed, with any numbers, before the first one is not?

echo preg_replace('/(\d+)/', '$1', '44f6&sor5t'); 

should bring 44

  • php.net/manual/ru/function.preg-replace.php Pay attention to the 4th parameter of the function - the limit of replacements. everything changes by default - Mike
  • echo preg_replace ('/ (\ d) + \ 1 /', '$ 1', '44f6 & sor5t', 1) does not work; - DivMan
  • @Mike I need to perform a replacement - DivMan
  • @Mike like this echo preg_replace ('/ (\ d +). * /', '$ 1', '44f6 & sor5t') ;, but what does this dot and asterisk mean? - DivMan
  • ru.wikipedia.org/wiki/... dot โ€” any character, asterisk โ€” 0 or more such symbols โ€” Mike

1 answer 1

preg_raplace () replaces only those parts of the string that fall under the search expression. All characters that do not fall under the expression - remain unchanged.

 echo preg_replace('/(\d+).*/', '$1', '44f6&sor5t'); 

will result in 44 . Part .* Means 0 or more of any characters, as a result, the expression can be read as "Replace the numbers (what is in the first brackets) and any characters following them with numbers ."