1

だから私はC++に翻訳したいそのようなphp関数を持っています:

protected function htmlTag($content, $tag, $attrName, $attrValue, $valueName)
{
    preg_match_all("#<{$tag}[^>]*$attrName=['\"].*?$attrValue.*?['\"][^>]*$valueName=['\"](.+?)['\"][^>]*/?>#i", $content, $matches1);
    preg_match_all("#<{$tag}[^>]*$valueName=['\"](.+?)['\"][^>]*$attrName=['\"].*?$attrValue.*?['\"][^>]*/?>#i", $content, $matches2);

    $result = array_merge($matches1[1], $matches2[1]);
    return empty($result)?false:$result[0];
}

使用例:

            $location = $this->htmlTag($content, 'meta', 'http-equiv', 'X-XRDS-Location', 'content');
            $server   = $this->htmlTag($content, 'link', 'rel', 'openid.server', 'href');
            $delegate = $this->htmlTag($content, 'link', 'rel', 'openid.delegate', 'href');

(内容は の結果です$content= curl_exec($curl);)

preg_match_all- pattern で指定された正規表現に一致するすべての対象を検索し、それらを flags で指定された順序で一致に入れます。最初の一致が見つかった後、後続の検索は最後の一致の終わりから続行されます。

boost::regexp を使用して翻訳する方法は?

4

1 に答える 1

2

このようなもの:

boost::optional<std::string> htmlTag(const std::string& content,
    const std::string& tag, const std::string& attrName,
    const std::string& attrValue, const std::string& valueName)
{
    const std::string
        expr1 = boost::format("#<%1[^>]*%2=['\"].*?%3.*?['\"][^>]"
                "*%4=['\"](.+?)['\"][^>]*/?>#i")
                % tag % attrName % attrValue % valueName,
        expr2 = boost::format("#<%1[^>]*%2=['\"](.+?)['\"][^>]*"
                "%3=['\"].*?%4.*?['\"][^>]*/?>#i")
                % tag % attrName % attrValue % valueName;

    boost::match_results<std::string::const_iterator>
        matches1, matches2, result;

    // do the searches (note: these probably need to be loops as shown at the bottom of this page:
    // http://www.boost.org/doc/libs/1_47_0/libs/regex/doc/html/boost_regex/ref/regex_search.html
    if (!regex_search(content, matches1, expr1))
        return boost::none;
    if (!regex_search(content, matches2, expr2))
        return boost::none;

    result = // merge matches1[1] and matches2[1] somehow
    if (result.empty())
        return boost::none;
    else
        return result[0];
}

いくつかの詳細が間違っていると確信しています(たとえば、コメントに従ってregex_searchを何度も呼び出す必要があると思います)が、うまくいけば、それらの詳細を理解して、完成したソリューションを投稿できます。

于 2011-07-17T16:58:08.490 に答える