所以我有这样的php函数,我想翻译成C++:
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中给出的正则表达式的所有匹配项,并将它们按标志指定的顺序放入匹配项中。找到第一个匹配项后,从最后一个匹配项的结尾继续进行后续搜索。如何使用boost::regexp进行翻译?
最佳答案
像这样:
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),但是希望您可以解决这些细节并发布完成的解决方案。
关于php - PHP`preg_match_all`函数的Boost::regex模拟将是什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6725035/