dongtaigan1594
2012-04-15 20:39
浏览 136
已采纳

xPath - 你能从节点中删除逗号吗?

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
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douxian4376 2012-04-15 23:41
    已采纳

    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.

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • doushi8231 2012-04-15 20:41

    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).

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题