2017-10-01 3 views
0

例文字列に正規表現で文字列内の任意の変数の単語を検索するには:はどのようにPHP

Here are sample apartment pictures {img="/path/photo1.jpg" alt="I am Photo Title"} and {img="/path/photo2.jpg" alt="I am Photo Title #2"} this... 

彼らが発見されなければならない:これらの画像リンクが文章に

{img="/path/photo1.jpg" alt="I am Photo Title"} 
{img="/path/photo2.jpg" alt="I am Photo Title 2"} 

を見つけることができますか?

+0

あなたがregex101または同様に試したことがありますか? – Andreas

+0

はい、 'regex'はそのためのいくつかのGoogleの結果であなたを助けます。特定の問題に遭遇しましたか? – mario

+1

@アンドレアスあなたはダウンスコアを与えたと思います。私はRegexを使用する方法がわからないので、私は質問する –

答えて

0
<?php 

$string = "Here are sample apartment pictures {img='/path/photo1.jpg' alt='I am Photo Title'} and {img='/path/photo2.jpg' alt='I am Photo Title #2'} this..."; 

preg_match_all("/({([\w]+)[^}]*})(.*?)/", $string, $matches, PREG_SET_ORDER); 

foreach ($matches as $val) { 
    echo "Variable Word In String: " . $val[1] . "<br>\n"; 
} 


?> 
0

爆発でも行うことができます。
ここで私は "{"最初に "img ="で始まらない配列内の項目を削除します。
次に、右側の余分を取り除くために "}"を爆発させます。

正規表現の代わりに正規表現やstrposよりも優れていると言っているわけではありません。

$str ='Here are sample apartment pictures {img="/path/photo1.jpg" alt="I am Photo Title"} and {img="/path/photo2.jpg" alt="I am Photo Title #2"} this...'; 

$arr = explode("{", $str); 
Foreach($arr as $key => &$val){ 
    if(substr($val,0,4) == "img="){ 
     $val = "{". explode("}", $val)[0] . "}"; 
    }else{ 
     Unset($arr[$key]); 
    } 
} 
Var_dump($arr); 

https://3v4l.org/7Zov0