获取两个字符串之间的字符串[PHP]
好吧,这可能是所有的互联网,但我找不到一个解决方案,一直在搜索和尝试不同的方式 因此,到目前为止,我尝试的主要方法如下: 字符串:获取两个字符串之间的字符串[PHP],php,preg-match,Php,Preg Match,好吧,这可能是所有的互联网,但我找不到一个解决方案,一直在搜索和尝试不同的方式 因此,到目前为止,我尝试的主要方法如下: 字符串: <div data-image-id="344231" style="height: 399.333px; background-image: url("/website/view_image/344231/medium"); background-size: contain;"></div> 我猜我不能用: 背景图像:url(“和”)而不
<div data-image-id="344231" style="height: 399.333px; background-image: url("/website/view_image/344231/medium"); background-size: contain;"></div>
我猜我不能用:
背景图像:url(“
和”)代码>而不是preg\u匹配
有没有人能给我一些指导,告诉我如何获得:
“/website/view\u image/344231/medium”
如果对背景图像url使用单引号而不是双引号,则可以使用并从div获取样式属性
然后使用explode(;”
,它将返回一个数组,其中该数组的一项将是“background image:url('/website/view_image/344231/medium')”
循环遍历数组并与正则表达式一起使用,例如背景图像:url\([^)]+)\
,它将在一组中捕获括号之间的内容
如果存在正则表达式匹配项,则存储组中的值
$html = <<<HTML
<div data-image-id="344231" style="height: 399.333px; background-image: url('/website/view_image/344231/medium'); background-size: contain;"></div>
HTML;
$doc = new DOMDocument();
$doc->loadHTML($html);
$elm = $doc->getElementsByTagName("div");
$result = array ();
$style = $doc->getElementsByTagName("div")->item(0)->getAttribute("style");
foreach (explode("; ", $style) as $str)
if (preg_match ('/background-image: url\(([^)]+)\)/', $str, $matches)) {
$result[] = $matches[1];
}
echo $result[0];
$html=getElementsByTagName(“div”)->item(0)->getAttribute(“样式”);
foreach(分解(“;”,$style)为$str)
if(preg_match('/background image:url\([^)]+)\/',$str,$matches)){
$result[]=$matches[1];
}
echo$result[0];
这将给你:
“/website/view_image/344231/medium”
我认为您需要跳出urlurl\(
和第二个右括号\)后的第一个括号。
@Dale请检查更新的问题-如何在带有“
添加到字符串中?@mega6382-如果这是一个小问题,请尝试解决问题-谢谢。@ChrisBeckett尝试使用单引号作为背景图像url。并使用这个正则表达式捕获它背景图像:url\('(.*?)代码>
$html = <<<HTML
<div data-image-id="344231" style="height: 399.333px; background-image: url('/website/view_image/344231/medium'); background-size: contain;"></div>
HTML;
$doc = new DOMDocument();
$doc->loadHTML($html);
$elm = $doc->getElementsByTagName("div");
$result = array ();
$style = $doc->getElementsByTagName("div")->item(0)->getAttribute("style");
foreach (explode("; ", $style) as $str)
if (preg_match ('/background-image: url\(([^)]+)\)/', $str, $matches)) {
$result[] = $matches[1];
}
echo $result[0];