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:
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!