0

I have been trying to take out some value from a string in php but not getting success so if you people can please take a look at my code as :

$html = "[ect]afdbec[ect]";
$output =true;
$x=1;

while ($output == true) {
$pos = strpos($html,"[");
$value = substr($html,$pos,$x);
echo $value;
$x++;
if ($value == "]") { $output = false; }
}

2 Answers2

2

I think your issue might be that you're checking when $value is equal to "]" (in the if-statement), but $value will never be just one character; you're asking it to always substr() from the position of the first "[".

You might want to have a look at preg_match() - there's a slight learning curve if you're new to it, but it'll help with this situations in future development.

roycable
  • 301
  • 1
  • 9
1

Put the line $pos = strpos($html,"["); outside the while loop. Because, it initializes the value of $pos to the position of "[" in each iteration of the loop. I don't think it will solve this problem.

Please get used to preg_match(). There will be a lot more simple way to do it.

Please try:

$html = "[ect]afdbec[ect]";
preg_match('~\[(.*?)\]~', $html, $match);
echo $match[1];

Please look here also

Community
  • 1
  • 1
Anoop S
  • 141
  • 1
  • 12