Php 如何从html文本中出现的img标记的src值中删除filepath子字符串?

Php 如何从html文本中出现的img标记的src值中删除filepath子字符串?,php,regex,preg-replace,filenames,src,Php,Regex,Preg Replace,Filenames,Src,我有一些值需要删除它们的路径 不幸的是,我的HTMLDOM是无效的,所以我不能使用DOM解析器,必须求助于正则表达式 我目前的尝试是: src=(\'|")\/root\/images\/([^\/]*)\/([^(\'|"]*) 要扭转这一局面: lots of other html <img src="/root/images/ANY MORE PATH HERE/file.jpg"> more html 为此: lots of other html <img src=

我有一些值需要删除它们的路径

不幸的是,我的HTMLDOM是无效的,所以我不能使用DOM解析器,必须求助于正则表达式

我目前的尝试是:

src=(\'|")\/root\/images\/([^\/]*)\/([^(\'|"]*)
要扭转这一局面:

lots of other html
<img src="/root/images/ANY MORE PATH HERE/file.jpg">
more html
为此:

lots of other html
<img src="file.jpg">
more html
如果我只使用capture group 3,并且在/root/images之外有一个目录,但我不知道在给定的文件路径中有多少子目录,那么上面的方法就行了


有什么建议吗?

我认为这是一个使用explode的简单解决方案:

 $src = "/root/images/ANY MORE PATH HERE/file.jpg";
 $part = explode("/", $src);
 $imageName = $part[sizeof($part)-1]; //get the last index of the array

这将使用preg_替换:

<?php
$foo = '/\/.+\//';
$test =  '<img src="/root/images/ANY MORE PATH HERE/file.jpg">';
echo preg_replace($foo, '', $test);
?>

在我看来,您可以匹配零个或多个非引号字符,后跟一个斜杠-尽可能多次,并用空字符串替换该子字符串。这将始终为您留下一个src值,该值完全由路径末尾的文件名组成

代码:


如果总是只需要文件名,请使用basename函数。要做到这一点,我必须取出所有的img标记,处理它们,然后将它们放回内存中。HTML是无效的吗?也有类似的问题,其结果是使用解析器或dom。因此,如果您可以修复其中的HTML部分,这可能会更好?只是字符串的一小部分,只要图像名称在末尾,这段代码就可以工作。打印出来并试一试。这仅在整个字符串是单个src属性值时有效。这不是OP所要处理的。稍微有点变化,这让我找到了正确的答案,谢谢。只有当整个html字符串是一个图像标记时,这才有效。这不是OP正在处理的问题。
$html = <<<HTML
lots of other html
<img src="/root/images/ANY MORE PATH HERE/file.jpg">
more html
HTML;

echo preg_replace('~ src=[\'"]\K(?:[^\'"]*/)*~','',$html);
lots of other html
<img src="file.jpg">
more html
~          #pattern delimiter (deliberately not slash -- to avoid escaping)
 src=      #match a space followed literally by "src="
['"]       #match either single quote or double quote
\K         #restart the fullstring match (effectively forget previously matched characters)
(?:        #start of non-capturing group
  [^'"]*   #match zero or more non-single and non-double quote characters
  /        #match a forward slash
)          #end of non-capturing group
*          #allow zero or more occurrences of the non-capturing group
~          #pattern delimiter