Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/250.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 检查字符串中的img src关键字_Php_Regex_Strpos - Fatal编程技术网

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

Php 检查字符串中的img src关键字,php,regex,strpos,Php,Regex,Strpos,我有一个博客系统,用户在博客内容中输入图像url,如 hey how are you <img src="example.com/image.png"> 当我回音时,我只得到: <img src=" 我想要完整 <img src="hey.png"> 如何从该字符串执行此操作。strpos返回指针在干草堆中起始位置的索引。查看将返回值与substr和haystack组合以获得所需的子字符串 由于图像src是未知的,请使用regex,类似这样的内容(

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

hey how are you <img src="example.com/image.png"> 
当我回音时,我只得到:

 <img src="

我想要完整

<img src="hey.png"> 


如何从该字符串执行此操作。

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

由于图像src是未知的,请使用regex,类似这样的内容(我不知道,所以可能语法不正确):

$string=“你好”;
$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">
)
数组
(
[0] => 
)

查看以了解更多详细信息。

这可能是一种更容易使用的方法

下面是一个简单的例子:

$string = 'hey how are you <img src="example.com/image.png"> blah blah';
preg_match('/<img src=".*">/', $string, $matches);
print_r($matches);
$string='嘿,你好吗;
preg_匹配('/',$string,$matches);
打印(匹配项);
这将为您提供如下数组:

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

这应该适合您:

$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]);
输出:



您应该改用regex.regex,
preg\u match(“/(/”,$string,$img\u标记);
@chris85我又遇到了一个问题,如果用户输入两次,那么preg\u match会同时显示img标记和这两个图像之间的所有文本。我只想要一个图像标记。在下面贴了一个答案,我认为应该可以解决您的问题。@chris85仍然在下面显示两个图像array@abhishekverma太好了,请接受这个答案在case;。我不能投票支持你的答案,因为我需要更多的4分才能开始投票answer@abhishekverma接受,而不是向上投票。你可以接受你曾经问过的每一个问题的答案。单击前面评论中的链接。
$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">
)
$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">
)
<?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">