2017-09-12 14 views
1

テキスト文字列から特定のURLを削除しようとしています。私はそれがほとんどの部分のために働いているが、私はhttpまたはhttpsリンクの両方のバージョンを含める必要があります。PHP特定のURLをhtml文字列から削除する

$link = '<a href="http://example.com/Tool/document.php?id=208" target="_BLANK">Document Requirementsd</a>'; 

$result = preg_replace('/<a href=\"http:\/\/' . $_SERVER["SERVER_NAME"] . '\/Tool\/document.php\?id=(.*?)\">(.*?)<\/a>/', "\\2", htmlspecialchars_decode($html)); 

httpとhttpsの両方のリンクが削除されていることを確認するにはどうすればよいですか?

答えて

4

(http|https):\/\/をhttpまたはhttpsに一致させることができます。

+4

または単に 'https?://'。 デリミタとして使用している場合は、スラッシュをエスケープしてください。 – thomasrutter

+0

良いキャッチ@thomasrutter。バックスラッシュを含めるように私の答えを編集しました。 –

0

だから、

$link = '&lt;a href=&quot;http://example.com/Tool/document.php?id=208&quot; target=&quot;_BLANK&quot;&gt;Document Requirementsd&lt;/a&gt;'; 
$link = '&lt;a href=&quot;https://example.com/Tool/document.php?id=208&quot; target=&quot;_BLANK&quot;&gt;Document Requirementsd&lt;/a&gt;'; 

右が必要ですか?

あなたは、リンクがHTTPまたはHTTPSであるかどうかを確認したい場合は、私が見つけるためにいくつかのより多くのコードを書くことができ、静的

//get primary link always http (we need to create http or https isset func) 
$link = '&lt;a href=&quot;http://example.com/Tool/document.php?id=208&quot; target=&quot;_BLANK&quot;&gt;Document Requirementsd&lt;/a&gt;'; 
//making that as https 
$https=str_replace('http','https',$link); 
//So now you can do whatever you want. 
$result = preg_replace('/<a href=\"http:\/\/' . $_SERVER["SERVER_NAME"] . '\/Tool\/document.php\?id=(.*?)\">(.*?)<\/a>/', "\\2", htmlspecialchars_decode($html)); 

としてHTTPを想定し置き換えることで、HTTPSリンクを取得使用

+1

str_replaceは、開始時以外の場所にリンクに "http"という文字列が含まれていると、正しく動作しません。リンクが一定であれば動作しますが、それはサンプルコードにすぎません。 – thomasrutter

+0

文字列にhttpまたはhttpsがあるかどうかを調べることでコードを再作成することができます(http部分のhttpをhttpsに置き換えてhttpsをチェックし、httpsをhttpに置き換えることができます) 次に、2つの文字列httpsとhttp –

関連する問題