| ||||||||||||
| ||||||||||||
Digging out embedded tags with preg_match_all() Posted by jamesbellamy (jamesbellamy), 28 October 2005 I am trying to use preg_match_all to extract the text between various custom tags starting with {{IF_:Code:
...which works fine when the tags come one after the other - it matches the contents of the IF_ONETHING tags and IF_YETANOTHER TAGS, but fails to match the IF_ANOTHER tags which are contained within the IF_ONETHING tags. I know that this is because preg_match_all carries on its search from the end of the first match. Is there any way to prevent this - have the next search start from the second character of the first match for instance? Posted by admin (Graham Ellis), 28 October 2005 How about using preg_match and capturing the offset, in a loop?Code:
Which gave me ... Code:
Example simplified to use easier tags, but I think it's the sort of thing? Posted by jamesbellamy (jamesbellamy), 31 October 2005 Thanks Graham. That would indeed be the perfect solution, except that I am lumbered with PHP 4.2.2 which is one version away from supporting offset capturing. The idea of offsets is now in my head however, so I'm going to try again with preg_match_all. I will post the results here.Posted by jamesbellamy (jamesbellamy), 3 November 2005 This is how I solved the problem (credit to my colleague Emily for the idea):In words, the solution is: 1) Do a preliminary search on the string 2) Add any results to 2 arrays, one with the tags still present, one without ($matchesTags and $matchesNoTags) - the results with tags included are the ones I am trying to find, but could be omitted otherwise 3) Count how many results were produced by the first search by counting the number of elements in the array 4) Now, in a loop, search through the array WITHOUT tags to see whether further results exist 5) If results DO exist, append them to the end of the two arrays created earlier (with array_push). 6) Count the number of array elements again. 7) Keep repeating the loop through the $matchesNoTags array until the index number of the loop equals the count of the array (ie. No further results have been found) Code:
This produces the result: Code:
All search results are neatly contained into one array with the added potential benefit that the array order is hierarchical - the most embedded tags will appear at the end of the array. I hope this helps somebody This page is a thread posted to the opentalk forum
at www.opentalk.org.uk and
archived here for reference. To jump to the archive index please
follow this link.
|
| |||||||||||
PH: 01144 1225 708225 • FAX: 01144 1225 793803 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho |