gpt4 book ai didi

php - 从文本 block 中提取和删除 URL

转载 作者:搜寻专家 更新时间:2023-10-31 20:45:59 25 4
gpt4 key购买 nike

我有这段文字:

$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>';

最佳答案

您需要将其存储在变量中还是只需要在 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>

关于php - 从文本 block 中提取和删除 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13309757/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com