3

次のテキスト ブロックがあります。

$text = 'This just happened outside the store http://somedomain.com/2012/12/store there might be more text afterwards...';

次のように変換する必要があります。

$result['text_1'] = 'This just happened outside the store';
$result['text_2'] = 'there might be more text afterwards...';
$result['url'] = 'http://somedomain.com/2012/12/store';

これは私の現在のコードです。URL は検出されますが、テキストから削除することしかできません。配列内で URL 値を個別に取得する必要があります。

$string = preg_replace('/https?:\/\/[^\s"<>]+/', '', $text);
//returns "This just happened outside the store  there might be more text afterwards..."

何か案は?ありがとう!

一時的な解決策(これを最適化できますか?)

$text = 'This just happened outside the store http://somedomain.com/2012/12/store There might be more text afterwards...';
preg_match('/https?:\/\/[^\s"<>]+/',$text,$url);
$string = preg_split('/https?:\/\/[^\s"<>]+/', $text);
$text = preg_replace('/\s\s+/','. ',implode(' ',$string));
echo '<a href="'.$url[0].'">'.$text.'</a>';
4

2 に答える 2

2

変数に格納する必要がありますか、それとも ahref 内に必要ですか? これはどう?

<?php
$text = 'This just happened outside the store http://somedomain.com/2012/12/store There might be more text afterwards...';
$pattern = '@(.*?)(https?://.*?) (.*)@';
$ret = preg_replace( $pattern, '<a href="$2">$3</a>', $text );
var_dump( $ret );

$1、$2、および $3 は、1 番目、2 番目、3 番目の括弧に対応します。

出力は次のようになります

<a href="http://somedomain.com/2012/12/store">There might be more text afterwards...</a>
于 2012-11-09T14:43:17.800 に答える
1

preg_splitを使用して正規表現で文字列を分割し、配列を取得できます

$result = preg_split('/(https?:\/\/[^\s"<>]+)/', $the_string, -1, PREG_SPLIT_DELIM_CAPTURE);
// $result[0] = preamble
// $result[1] = url
// $result[2] = possible afters
于 2012-11-09T14:22:57.547 に答える