Let’s say we have a text as follows:
Hello this is a sentence and some text. In this text only we have the following expression:
..and then this text continues.
Now, in my code, I am getting the above text in a variable, let’s say variable named “content”.
So what I want is parse this variable, and get everything enclosed in tags [temptag] and [/temptag] first.
After we get that, extract the variables enclosed within this tag, in their respective variables. So, in type=file combo, type will be stored in a new variable named as “type” and its value “file” in that variable. In other words, after parsing this in code, I should have the following variables to play with in my code - type, file, mode, width, height. Please note that these variables may not be necessary in the same order, and they some of them may not be present at all betwene those tags.
Can someone help writing me a code for this please?
Well without writing the function entirely definitely look into using substr(). You can find the positions of [temptag] and [/temptag] respectively, and use substr to cut out the middle and set that to your $content variable.
So you may have possibly 5 tag=x variables in between these tags always with a pipe in between them…
$contentPieces = explode("|", $content);
// contentPieces[1-5] are now set to each of your combinations...assuming all are set
foreach ($contentPieces as $contentPiece)
if (stristr($contentPiece, "type=")!=false) // if type= exists as one of the sets
$typePieces = explode("=", $contentPiece);
$typePieces is set to type
$typePieces is set to whats on the other side of the equals sign
$type = $typePieces;
/* Fill in with the same concept with the rest of the parameters, file, width, mode, height, etc */
Definitely not the most efficient way to do it but that should give you a rough idea of what to do.
I guess using pregmatch all should be a better option?
I tried something like this, but doesn’t work…may be something wrong in the expression:
preg_match_all("/\\[temptag\\](.*?)\\[\\/temptag\\]/", $content, $matches);
Yeah, I’d do preg_match() or preg_match_all() and then a couple rounds of explode(). Your pattern looked good to me, so I tried it with the sample code you posted and it worked for me.