I need to do some text processing tasks with short XML fragments. The section "details" shows an example... My solution is to use a tokenizer based on regular expresions, but it is not elegant and not uses any build-in function. The candidate build-in functions (that others indicates to me) are strtok and SimpleXML.
So, my question have two parts:
My assumptions are correct? There are no other "candidates", only strtok and SimpleXML? Is correct to think DomDocument as an "elephant" (with big CPU overhead) for a simple text processing task?
How to use SimpleXML to do the same (illustred) task? PS: I not need all algorithm or implementation, only some clues.
Details
PHP offers a tokenizer, strtok, very simple, and I not see how to use it with XML string. The option, SimpleXML, is perhaps heavy for tasks like ''text processing'' (see this example and the below), and is more than a tokenizer.
What exactly I whant to say with "tokenizer" and "text processing"? See example below. I used a "regex parser", but I would like an algorithm based on some built-in function like SimpleXML, if it is simpler and faster.
$xmlFrag = '
<p align="center"> Hello world!</p>
<p class="test"><i> Beautiful</i> day today.</p>';
// TOKENIZING TAGS AND ENTITIES:
$reg=array();
$xmlFrag = preg_replace_callback(
'/<!\-\-.+?\-\->|<.+?>|&[a-z0-9]+;/is',
function ($m) {
global $reg; $reg[]=$m[0]; $n=count($reg)-1;
return "##$n#";
},
$xmlFrag
);
echo $xmlFrag; // results:
// ##0###1# Hello world!##2# ##3###4###5# Beautiful##6# day today.##7#
// PROCESS THE TEXT: any, in one step. Example: lower, upper, change orthography, etc.
$xmlFrag = strtoupper($xmlFrag);
echo $xmlFrag;
// ##0###1# HELLO WORLD!##2# ##3###4###5# BEAUTIFUL##6# DAY TODAY.##7#
// EXPAND TOKENS:
$xmlFrag = preg_replace_callback(
'/##([0-9]+)#/is',
function ($m) { global $reg; return $reg[$m[1]]; },
$xmlFrag
);
echo $xmlFrag;
// <p align="center"> HELLO WORLD!</p>
// <p class="test"><i> BEAUTIFUL</i> DAY TODAY.</p>
Using SimpleXML
How to implement a SimpleXML algorithm to resolve the illustrated problem (code above)? PROBLEMS:
- Load a XML with named entities (as
in the example). - Traverse XML to get only text nodes. With
$sx->xpath('//text()');
I can not edit the nodes.
Using DomDocument
It is out of context, because my XML fragments are short and DomDocument imposes a big CPU overhead (? is this a preconception?) for the simple text processing.