사이트 내 전체검색
PHP
내용중 이미지 태그 부분만 추출하기
로빈아빠
https://cmd.kr/php/35 URL이 복사되었습니다.

본문

Q:
<IMG alt=P41904.jpg src="files/attach/images/304/440/P41904.jpg" editor_component="image_link"><IMG alt=P41899.jpg src="files/attach/images/304/440/P41899.jpg" editor_component="image_link">

저는 저장된 값중 "files/attach/images/304/440/P41904.jpg" , "files/attach/images/304/440/P41899.jpg" 2개의 값을 배열에 집어 넣고 싶은데.. 어떻게 해야 되나여

A:
<?
    $buff = Array(); // 결과 저장 배열

    $input = '<IMG alt=P41904.jpg src="files/attach/images/304/440/P41904.jpg" editor_component="image_link"><IMG alt=P41899.jpg src="files/attach/images/304/440/P41899.jpg" editor_component="image_link">';
    preg_match_all("/<img [^<>]*>/is",$input,$output);

    foreach($output[0] as $value) {
            $content = $value;

            if(eregi("[:space:]*(src)[:space:]*=[:space:]*([^ >;]+)",$content,$regs)) {
                $regs[2] = str_replace(Array("'",'"'),"",$regs[2]);
                $buff[] = $regs[2];
            }
    }

    echo "<xmp>";
    print_r($buff);
    echo "</xmp>";
?>

/* 결과 */

Array
(
    [0] => files/attach/images/304/440/P41904.jpg
    [1] => files/attach/images/304/440/P41899.jpg
)


A:
<?
    $input = '<IMG alt=P41904.jpg src="files/attach/images/304/440/P41904.jpg" editor_component="image_link"><IMG alt=P41899.jpg src="files/attach/images/304/440/P41899.jpg" editor_component="image_link">';
    preg_match_all('/src=\"(.[^"]+)"/i', $input, $value);
    print_r($value[1]);
?>
output :
Array
(
    [0] => files/attach/images/304/440/P41904.jpg
    [1] => files/attach/images/304/440/P41899.jpg
)

----------------------------
Q:
배틀제이님 // 감사합니다 ^^
그런데 <IMG src = "abc.gif">
이렇게 src 다음에 빈칸 있을 경우는 어떻게 하면 되겠습니까? ^^;;
그리고 <IMG src = 'abc.gif'>
이렇게 홑따옴표인 경우는 어떻게 하면 좋겠습니까?
이것 때문에 마음 고생이 심합니다.

---------------------------------------
A:
$cnt = preg_match_all('@<img\s[^>]*src\s*=\s*(["\'])([^\s>]+?)\1@i';, $html, $matches);
print_r($matches[2]);

대충 경우의 수를 넣었습니다.

$cnt = preg_match_all('@<img\s[^>]*src\s*=\s*(["\'])?([^\s>]+?)\1@i',$input,$output);

    echo "<xmp>";
    print_r($output[2]);
    echo "</xmp>";

--------------------------------

<img[^<>*]> 는 <img.*?> 와 결과가 같습니다. 단점으로는 따옴표 안에 있는 문자까지 테그의 끝으로 취급해서 잘못 체크된다는 것이죠.

이런 문제를 해결하기 위해서는 따옴표를 따로 체크하면 됩니다.
preg_match_all(
        '!<img\s+(?:[\w\d_\s=]+(?:"[^"\\\\]*(?:[^"\\\\]*)*"|\'[^\'\\\\]*(?:[^\'\\\\]*)*\'|[^\s]+)\s+)+/?>!is',
        $content,
        $matches
);


링크를 추출한 뒤에 각 속성을 얻기 위해서는
preg_match_all(
      '!(?:([\w\d_]+)\s*=\s*("[^"\\\\]*(?:[^"\\\\]*)*"|\'[^\'\\\\]*(?:[^\'\\\\]*)*\'|[^\s]+)\s+)!is',
      $tag,
      $matches
);

$upload_name  = strtolower($upload_name); //소문자로 강제변환
        $UpFileName  = explode(".", $upload_name);
        $UpFileType  = $UpFileName[count($UpFileName) - 1]; //파일이름에서 .이 여러개 있을경우 마지막 .으로 확장자와 파일이름 구분
    if(eregi("jpg|gif|png", $UpFileType)) {
                      ******
              }

댓글목록

등록된 댓글이 없습니다.

PHP
871 (1/18P)

Search

Copyright © Cmd 명령어 3.15.239.140