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 回答