アプリ版:「スタンプのみでお礼する」機能のリリースについて

<?php echo $field;?>

この$fieldの中にはhtmlソースが入っています。

そして、echo する前に、そのhtmlソースにあるURLのうちhttp://で始まっているものをすべて、
ドキュメントルートからの絶対パスに置換したいのですが、
どのように書けばいいでしょうか?

例)

http://localhost/foo/bar.jpg → /foo/bar.jpg

以上、よろしくお願い申し上げます。

質問者からの補足コメント

  • localhostの部分はいろいろなFQDNを想定しています

      補足日時:2015/01/30 15:07
  • ありがとうございます。元がURLならそれでいけそうですね。
    ただ、元がHTMLソースなので、ご回答をどう活かしていいのかわかりません。
    どうご回答とHTMLソースをつなげればいいのでしょうか?

    No.1の回答に寄せられた補足コメントです。 補足日時:2015/01/30 15:40

A 回答 (3件)

htmlソースだと、タグに埋め込まれているかもしれないのですね



後ろに何がきたらurlの終わりか考えておく必要があるかも

<?PHP
$field=<<<eof
test
test<a href="http://localhost/foo/bar.jpg">http://localhost/f …
test<a href='http://localhost/foo/bar.jpg'>http://localhost/f …
testhttp://localhost/hoge/fuga.html
testhttp://localhost/hoge/fuga.html http://localhost/hoge/fuga.html http://localhost/hoge/fuga.html test
test
eof;
print "<pre>";
print htmlspecialchars($field);
print "<hr>";

$pattern="/(http:.+?(?=['\"<\s]|$))/";
$field=preg_replace_callback($pattern,function ($matches){
return parse_url($matches[1])["path"];
},$field);

print htmlspecialchars($field);
print "</pre>";
    • good
    • 1
この回答へのお礼

ありがとうございます。できました!感謝です

お礼日時:2015/02/02 11:22

失礼しましたhtmlソースの置換でしたね


こんな感じでどうでしょう?
「http:」から始まってスペースか行末までの文字列を変換

<?PHP
$str=<<<eof
test
http://localhost/foo/bar.jpg
test
http://localhost/hoge/fuga.html
http://localhost/hoge/fuga.html test
testhttp://localhost/hoge/fuga.html http://localhost/hoge/fuga.html http://localhost/hoge/fuga.html test
test
eof;
print "<pre>";
print $str;
print "<hr>";

$pattern="/http:.+?(?=\s|$)/";
$str=preg_replace_callback($pattern,function ($matches){
return parse_url($matches[0])["path"];
},$str);

print $str;
print "</pre>";
?>
    • good
    • 0

urlが正しい文法で書かれているのであればparse_url()でよろしいかと



<?PHP
$str="http://localhost/foo/bar.jpg";
print parse_url($str)["path"];
?>

ちなみに
<?PHP
$str="http://localhost/foo/bar.jpg";
$parseurl=parse_url($str);
print_r($parseurl);
?>
この回答への補足あり
    • good
    • 0

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!