php
  • regex
  • preg-replace
  • 2017-10-01 10 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

    パターンには1つのキャプチャグループしかありません。 –

    +0

    https://ideone.com/vJHTsm –

    +1

    を参照してください。@WiktorStribiżew私はあなたがダウンタウンを与えたと思うが、あなたは同時に反応した。あなたの答えをありがとう。あなたが望むなら、答えを書くことができます。私はあなたの答えを正確に記したいと思っています –

    答えて

    0

    ({\w+)パターンは、グループ1に一致し、キャプチャして、中括弧の後ろに{と1つ以上の単語文字のみをキャプチャします。あなたの取り替えパターンには、捕捉グループが1つしかないので、「働かない」置換逆参照が$1$2にあります。

    あなたはPHP 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); 
    

    を使用することができ、出力

    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を参照してください。

    詳細

    • {# - サブ{#
    • \w+ - 1以上の文字、数字または/および_
    • ='から='リテラルストリング
    • ([^']*) - グループ1: '以外の0文字以上
    • 'から'
    • \s*,\s* - 0+空白
    • \w+=で囲まれ、コンマ - 1またはそれ以上の文字、数字および/または_='
    • 'から'
    • ([^']*) - グループ2 :'
    • '} - a '}文字列以外の0以上の文字。
    関連する問題