我有以下字符串:
1)search #test
2)search https://example.com/search#test".
3)searchhttps://example.com#test"
我需要将其转换为:
第一个喜欢
search <a href="https://example.com/search?q=test" target="_blank">#test</a>
第二个应该是简单的网址 -
search <a href="https://example.com/search#test" target="_blank">https://example.com#test</a>
第三个应保持相同
searchhttps://example.com#test"
答案 0 :(得分:0)
第一
$pattern = '/search\s(#)+(.+)/';
$string = "search #test";
$string = preg_replace($pattern, 'search <a href="https://example.com/search?q=\2" target="_blank">https://example.com#\2</a>', $string);
echo $string;
第二
$pattern = '/search\s(http(s)*(.*))(#)+(.+)/';
$string = "search https://example.com/search#test";
$string = preg_replace($pattern, 'search <a href="https://example.com/search#\5" target="_blank">#\5</a>', $string);
echo $string;
只需应用第一个,然后将第二个应用于您要处理的文本。
$pattern = '/search\s(#)+(.+)/';
$string = "whateveryouwant";
$string = preg_replace($pattern, 'search <a href="https://example.com/search?q=\2" target="_blank">https://example.com#\2</a>', $string);
$pattern = '/search\s(http(s)*(.*))(#)+(.+)/';
$string = preg_replace($pattern, 'search <a href="https://example.com/search#\5" target="_blank">#\5</a>', $string);
修改强>
第二种情况,通用网址
$pattern = '/search\s(http(s)*(.*))(#)+(.+)/';
$string = preg_replace($pattern, 'search <a href="\1#\5" target="_blank">#\5</a>', $string);
对于第一种情况,不能识别网址。