检查字符串中的img src关键字


Check for img src keyword in a string

我有一个博客系统,用户在其中输入文章内容中的图像url,如

hey how are you <img src="example.com/image.png"> 

如果用户像这样写

hello how are you <img src="example.com/image.png">

然后我想找到这条img src线,并将其用作特征图像

这是我尝试过的:

$haystack = 'how are you <img src="hey.png">';
$needle = '<img src="';
if (strpos($haystack, $needle) !== false) {
    echo "$needle";
}
else { echo "no"; }

当我回应时,我只得到:

 <img src="

我想得到整个

<img src="hey.png"> 

从那根绳子我怎么能做到这一点。

这应该适用于您:

$string = 'hey how are you <img src="example.com/image.png"> test test <img src="example.com/image2.png">';
preg_match_all('/(<img .*?>)/', $string, $img_tag);
print_r($img_tag[1]);

输出:

Array
(
    [0] => <img src="example.com/image.png">
    [1] => <img src="example.com/image2.png">
)

不过,您应该考虑为此使用解析器。它们已经内置了比正则表达式多得多的功能,并且将清除错误。

Regex101:https://regex101.com/r/iY1wX0/1

或者,如果你真的只想要第一个img,就使用preg_match

<?php
$string = 'hey how are you <img src="example.com/image.png"> test test <img src="example.com/image2.png">';
preg_match('/(<img .*?>)/', $string, $img_tag);
echo $img_tag[1];

输出:

<img src="example.com/image.png">

strpos返回指针在干草堆中起始位置的索引。将返回的值与substrhaystack组合以获得所需的子字符串。

由于图像src是未知的,请使用regex,类似这样的东西(在我的脑海中,所以它可能是不正确的语法):

$string = "hey how are you <img src='"example.com/image.png'">"; 
$return = preg_match('/src="([^"]+)"/', '$string', $matches);

您可以使用正则表达式来匹配该字符串。我离开php已经很久了。。。所以它是这样的:

<?php
  $pattern = '/<img'ssrc'=".*?">/';
  $haystack = 'how are you <img src="hey.png">';
  preg_match($pattern, $haystack, $matches);
  print_r($matches);
?>

结果将是

Array
(
    [0] => <img src="hey.png">
)

查看preg_match()了解更多详细信息。

使用正则表达式(RegEx)可能更容易做到这一点。

这里有一个简单的例子:

$string = 'hey how are you <img src="example.com/image.png"> blah blah';
preg_match('/<img src=".*">/', $string, $matches);
print_r($matches);

这会给你一个这样的数组:

Array
(
    [0] => <img src="example.com/image.png">
)