I have an xPath query that grabs plaintext from a div like this
xpath->query("//div[@id='main']//span[@class='meta']/text()")
This query returns The text that I want,
Is there anyway that I can remove that comma within my query?
Thanks
EDIT:
Using Mad's code from below, my query now looks like this (I've replaced the ,
in the example with the word hello
to make it a bit less confusing.)
$search_term = $xpath->query("translate('//div[@id='main']//span[@class='meta']/text()', 'hello', '')");
And I'm attempting to echo the query results like this:
foreach ($search_term as $st) {
echo $st->nodeValue; }
The error I'm receiving is
Invalid argument supplied for foreach() in ... on line 50
You could use translate()
to replace the ,
character with empty an string:
xpath->query("translate(//div[@id='main']//span[@class='meta']/text(), ',', '')")
Although, it could result in a trailing space if the comma was preceded or followed by a space in the text()
node.
You could then use normalize-space()
to remove leading/trailing whitespace:
xpath->query("normalize-space(translate(//div[@id='main']//span[@class='meta']/text(), ',', ''))")
Although, it will also normalize sequences of whitespace in the middle of the text into single spaces.
You could also use substring-before()
to select the text preceding ,
:
xpath->query("substring-before(//div[@id='main']//span[@class='meta']/text(), ' ,')")
However, if the string does not contain ,
then substring-before()
will not return anything.
Looks like rtrim
is the better choice if you want to remove a trailing comma. I don't see why involving the XPath with this would be preferable, but you could also do it with the fn:replace
function (XPath 2.0).