mauro26 0 Denunciar post Postado Junho 19, 2015 Oi tudo bem? Precisava de uma ajuda em expressões regulares, não é o meu forte. Eu basicamente tenho numa string um tag assim -> [34] Basicamente quero usar essa tag para pegar o seu numero que é o id e depois fazer a query para pegar a informação relativa a ele. Sei que tenho que usar um padrão para descobrir ele no string e depois pegar os numeros dentro do brackets e a seguinte fazer a substituição que no meu caso vai ser por uma função. Alguem pode-me ajudar? Compartilhar este post Link para o post Compartilhar em outros sites
Beraldo 864 Denunciar post Postado Junho 19, 2015 Com preg_match (ou preg_match_all, se houver mais de uma ocorrência na string), você pega os números exemplo: php > $str = 'texto texto [34] texto texto [21] mais texto [7] fim'; php > preg_match_all( "/\[([0-9]+)\]/", $str, $matches ); php > print_r( $matches ); Array ( [0] => Array ( [0] => [34] [1] => [21] [2] => [7] ) [1] => Array ( [0] => 34 [1] => 21 [2] => 7 ) ) Compartilhar este post Link para o post Compartilhar em outros sites
mauro26 0 Denunciar post Postado Junho 19, 2015 Obrigado Beraldo, mas so mais uma pergunta, eu criei um foreach loop foreach ($matches as $i => $row) { echo $row[$i] ."<br>"; } E o resultad é [45] 76 O problema é que o 45 tem o brackets e não quero que tenha, porque ele está assim e como remover o brackets? Compartilhar este post Link para o post Compartilhar em outros sites
Beraldo 864 Denunciar post Postado Junho 19, 2015 If matches is provided, then it is filled with the results of search. $matches[0] will contain the text that matched the full pattern, $matches[1] will have the text that matched the first captured parenthesized subpattern, and so on. fonte: http://php.net/preg_match Ou seja, somente o índice 1 lhe interessa. O índice 0 terá sempre os colchetes, pois é o valor que casou com a ER Por isso use $matches[1] no foreach foreach ($matches[1] as $i => $row) // ... Compartilhar este post Link para o post Compartilhar em outros sites