簡潔にするために...
文字列からアイテムを取り出して別の配列に入れ、文字列から抽出された値をIDトークンに置き換え、文字列を解析してから、抽出されたアイテムを元に戻します。元の位置(正しい順序で)。(それが理にかなっている場合は、残りをスキップしてください:D)
私は次の文字列を持っています。
「私の文章には[url]と[url]へのURLが含まれているため、私の生活は困難です。」
いろいろな理由で、URLを削除したいと思います。しかし、私はそれらの場所を維持し、後で(文字列の残りの部分を操作した後)それらを再挿入する必要があります。
したがって、私は欲しいです。
「私の文章には[url]と[url]へのURLが含まれているため、私の生活は困難です。」
になる;
「私の文章には[token1fortheURL]と[token2fortheURL]へのURLが含まれているため、私の生活は困難です。」
私はこれを何度か、さまざまな方法で試しました。私がしているのは、レンガの壁にぶつかって、新しい宣誓の言葉を発明することだけです!
次のコードを使用してセットアップします。
$mystring = 'my sentence contains URLs to http://www.google.com/this.html and http://www.yahoo.com which makes my life difficult.';
$myregex = '/(((?:https?|ftps?)\:\/\/)?([a-zA-Z0-9:]*[@])?([a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}|([0-9]+))([a-zA-Z0-9-._?,\'\/\+&%\$#\=~:]+)?)/';
$myextractions = array();
次に、preg_replace_callbackを実行します。
$matches = preg_replace_callback($myregex,'myfunction',$mystring);
そして、私は次のように私の機能を持っています。
function myfunction ($matches) {}
そして、ここでレンガの壁が起こり始めます。空白の抽出配列にデータを入れることはできますが、関数の外部では使用できません。文字列をトークンで更新できますが、置き換えられたURLにアクセスできなくなります。preg_replace_callback内の関数呼び出しに値を追加できないようです。
これが私を狂わせているので、誰かが助けてくれることを願っています。
アップデート:
@Lepidosteusによって提案された解決策に基づいて、私は次のように機能していると思いますか?
$mystring = 'my sentence contains URLs to http://www.google.com/this.html and http://www.yahoo.com which makes my life difficult.';
$myregex = '/(((?:https?|ftps?)\:\/\/)?([a-zA-Z0-9:]*[@])?([a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}|([0-9]+))([a-zA-Z0-9-._?,\'\/\+&%\$#\=~:]+)?)/';
$tokenstart = ":URL:";
$tokenend = ":";
function extraction ($myregex, $mystring, $mymatches, $tokenstart, $tokenend) {
$test1 = preg_match_all($myregex,$mystring,$mymatches);
$mymatches = array_slice($mymatches, 0, 1);
$thematches = array();
foreach ($mymatches as $match) {
foreach ($match as $key=>$match2) {
$thematches[] = array($match2, $tokenstart.$key.$tokenend);
}
}
return $thematches;
}
$matches = extraction ($myregex, $mystring, $mymatches, $tokenstart, $tokenend);
echo "1) ".$mystring."<br/>";
// 1) my sentence contains URLs to http://www.google.com/this.html and http://www.yahoo.com which makes my life difficult.
function substitute($matches,$mystring) {
foreach ($matches as $match) {
$mystring = str_replace($match[0], $match[1], $mystring);
}
return $mystring;
}
$mystring = substitute($matches,$mystring);
echo "2) ".$mystring."<br/>";
// 2) my sentence contains URLs to :URL:0: and :URL:1: which makes my life difficult.
function reinsert($matches,$mystring) {
foreach ($matches as $match) {
$mystring = str_replace($match[1], $match[0], $mystring);
}
return $mystring;
}
$mystring = reinsert($matches,$mystring);
echo "3) ".$mystring."<br/>";
// 3) my sentence contains URLs to http://www.google.com/this.html and http://www.yahoo.com which makes my life difficult.
それはうまくいくようですか?