php – Problem with regular expression


preg_match('<[ \w"=]+name="xhpc_composerid"[ \w="]+>',$exec,$result1);
echo $result1[0];
//input type="hidden" autocomplete="off" name="xhpc_composerid" value="u_0_1k" 

echo $result2[0];
// value="u_0_1k"

$result3 = preg_replace('/value="/i',"ab123",$result2[0]);
echo $result3[0];
// a

$result4 = substr($result3[0],0,-1);
echo $result4;
// (vazio)

The question is, $result2 value="u_0_1k" , why does $result3 print a ? My regex should be correct, I expected something like: u_0_1k" , then in $result4 would print what it printed in $result3 but without the double quotes, what can I be wrong?


I didn't fully understand what was being asked. Below is an example:

  • extracting some parts (xml attributes)
  • replacing a value with a new value.

based on your example


$exemplo='<xxx "type="hidden" autocomplete="off" name="xhpc_composerid" value="u_0_1k">';

preg_match('<.*? name="(.*?)".*? value="(.*?)".*?>',$exemplo,$result);
echo "id    encontrado foi...  $result[1]\n";
echo "valor encontrado foi...  $result[2]\n";

$r = preg_replace('/(value=")(.*?)"/',"$1Novo valor", $exemplo);
echo "$r\n";


when running ( php file ) produces:

id    encontrado foi...  xhpc_composerid
valor encontrado foi...  u_0_1k
<xxx "type="hidden" autocomplete="off" name="xhpc_composerid" value="Novo valor>
Scroll to Top