$texto = 'Foo #1 #2 Bar #23 Candy #22'; $texto = preg_replace_callback('/#(\d+)\b/', function($match) { return algo_que_hacer_con($match[1]); // el número },$texto);