Home  >  Article  >  Web Front-end  >  Can XPath Queries Become Case-Insensitive Using contains()?

Can XPath Queries Become Case-Insensitive Using contains()?

Susan Sarandon
Susan SarandonOriginal
2024-10-22 20:45:35849browse

Can XPath Queries Become Case-Insensitive Using contains()?

Case-Insensitive XPath contains() Function

Question:

Can XPath queries be made case-insensitive when using the contains() function to search for text nodes?

Answer:

Yes, case-insensitive XPath queries are possible using the following techniques:

Using translate() and contains():

This method involves translating the node value and the search string to lowercase before using the contains() function:

/html/body//text()[
  contains(
    translate(., 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'),
    'test'
  )
]

Using Host Language to Build Dynamic XPath Expression:

If possible, create a dynamic XPath expression using a host language like JavaScript:

<code class="javascript">function xpathPrepare(xpath, searchString) {
  return xpath.replace("$u", searchString.toUpperCase())
              .replace("$l", searchString.toLowerCase())
              .replace("$s", searchString.toLowerCase());
}

xp = xpathPrepare("//text()[contains(translate(., '$u', '$l'), '$s')]", "Test");</code>

This method translates only the necessary characters in the search string, making it suitable for any search term.

Considerations:

  • Both methods fail when search strings contain single quotes.
  • Using special elements like to mark relevant text can simplify XPath queries.

The above is the detailed content of Can XPath Queries Become Case-Insensitive Using contains()?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn