Home  >  Article  >  Web Front-end  >  How to Perform Case-Insensitive XPath Searching with ContainsIn Function?

How to Perform Case-Insensitive XPath Searching with ContainsIn Function?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-22 18:51:03198browse

How to Perform Case-Insensitive XPath Searching with ContainsIn Function?

Case-insensitive XPath Contains

In XPath, the contains() function checks if one string contains another, like this:

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

This is case-sensitive, meaning it won't match "Test," "TEST," or "TesT." To enable case-insensitivity, try this workaround:

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

This replaces every uppercase letter with its lowercase counterpart before checking for matches. However, it's limited to known character sets.

An alternative method leverages 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 allows for case-insensitive matching of any search string without prior knowledge of the alphabet. However, both options struggle with single quotes in search strings.

The above is the detailed content of How to Perform Case-Insensitive XPath Searching with ContainsIn Function?. 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