Problem with Regular Expression

Asked

Viewed 96 times

4

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

preg_match('/value="[\w]+"/i',$result1[0],$result2);
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 point is, $result2 print value="u_0_1k", why $result3 print a? My regex must be correct, I expected something like: u_0_1k", ai na $result4 would print out what you printed on $result3 only without double quotes, which I may be missing?

  • 2

    Now that I’ve noticed, print To probably why $result3[0], remove the [0] 'cause that way you’re taking the first letter only. echo $result3 // ab123u_0_1k"

  • 1

    Perfect! I thought it would return an array, but from what I read, it only returns array if the Subject of preg_replace is an array, that is, if the text to be Replacement is an array too, then it would return an array, so I ended up using $result3[0] intended to be messing with array, thank you for your attention!

  • 1

    Use an ER to directly access the value. It would not be better, or you modify the value during the process?

  • an ER to directly access the value? I couldn’t imagine how to do that.. for my case I believe not to, since the value may be at the beginning, in the middle of input attributes, so I did not consider the possibility of having 1 ER only..

  • I do not master ER, but if you modify your question I believe that someone with more knowledge can answer appropriately with an ER for you to solve your case.

  • Okay @Papacharlie, thanks for your help.

  • Okay, then with more time I create an answer with more explanation.

  • I don’t understand what you mean.

Show 3 more comments

1 answer

1

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

  • extraction of some parts (xml attributes)
  • replacement of a value (value) by a new value.

based on your example

<?php

$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 executing (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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.