php
  • regex
  • preg-replace
  • 2017-10-01 1 views -1 likes 
    -1
    $input_lines = 'this photos {img='3512.jpg', alt='Title'} and {#img='3513.jpg', alt='Title2'} any image code here related to image must be replaced.'; 
    echo preg_replace("/({\w+)/", "<img src='https://imgs.domain.com/images/$1' alt='$2'/>", $input_lines); 
    

    정규식 코드 :특정 링크

    /({\w+)/

    이미지 링크 :

    {img='3512.jpg', alt='Title'}와 문장 {img='3513.jpg', alt='Title2'}.

    변환 :

    this photos <img src='https://imgs.domain.com/images/3512.jpg' alt='Title'/><img src='https://imgs.domain.com/images/3513.jpg' alt='Title2'/> any image code here related to image must be replaced.

    나는 문장에있는 이미지 링크를 얻을 수 있지만 정규식 코드에 어떤 문제가 있습니까?

    +0

    패턴에 포착 그룹이 하나만 있습니다. –

    +0

    https://ideone.com/vJHTsm –

    +1

    @ WiktorStribiżew를보십시오. 당신은 아래쪽을 준다고 생각하지만 동시에 응답했습니다. 답해 주셔서 감사합니다. 원한다면 답을 쓸 수 있습니다.귀하의 답변에 정확하게 표시하고 싶습니다. –

    답변

    0

    ({\w+) 패턴은 열린 중괄호 뒤에 {과 하나 이상의 단어 문자 만 그룹 1과 일치하고 캡처합니다. 대체 패턴에는 캡처 그룹이 하나뿐이기 때문에 "작동"할 수없는 대체 하위 참조가 $1$2입니다.

    당신은

    this photos <img src='https://imgs.domain.com/images/3512.jpg' alt='Title'/> and <img src='https://imgs.domain.com/images/3513.jpg' alt='Title2'/> any image code here related to image must be replaced.

    regex demo을 참조 출력,

    $re = "/{#\w+='([^']*)'\s*,\s*\w+='([^']*)'}/"; 
    $str = "this photos {#img='3512.jpg', alt='Title'} and {#img='3513.jpg', alt='Title2'} any image code here related to image must be replaced."; 
    $subst = "<img src='https://imgs.domain.com/images/\$1' alt='\$2'/>"; 
    echo preg_replace($re, $subst, $str); 
    

    PHP demo 참조 사용할 수 있습니다.

    세부

    • {# - 문자열 {#
    • \w+ - 1 개 이상의 문자, 숫자 및/또는 _
    • =' - =' 리터럴 문자열
    • ([^']*) - 그룹 1 : '
    • 이외의 0 개 이상의 문자
    • '-1 이상의 문자, 숫자 및/또는 _='
    • ' - - '
    • ([^']*) - 그룹 2 '
    • \s*,\s* - 0+ 공백
    • \w+=에 동봉 쉼표 : '
    • '} - '} 문자열 이외의 0 개 이상의 문자.
    관련 문제