2014-11-06 2 views
-1

나는 다음과 같은 문자열이 있습니다 앵커 태그 설정

search <a href="https://example.com/search?q=test" target="_blank">#test</a> 

초 하나가 간단해야

첫 번째

같은 : 내가로 변환 할 필요가

1)search #test 

2)search https://example.com/search#test". 

3)searchhttps://example.com#test" 

을 url -

search <a href="https://example.com/search#test" target="_blank">https://example.com#test</a> 

thir D 하나

searchhttps://example.com#test" 
+1

시도한 바가 있습니까? –

+0

문자열에 해시 태그가 포함 된 특정 조건에서 HTML 앵커 태그를 문자열에 추가하고 싶습니다. –

+0

동일한 저자의 [문자열을 URL로 링크하는 방법은?] (http://stackoverflow.com/questions/26774799/how-to-linkify-urls-in-a-string-with-php) – smathy

답변

0

1

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

2

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

편집

2의 경우, 일반적인 URL을 첫 번째 경우를 들어

$pattern = '/search\s(http(s)*(.*))(#)+(.+)/'; 
     $string = preg_replace($pattern, 'search <a href="\1#\5" target="_blank">#\5</a>', $string); 

, 아니 URL을 인식 할 수 없습니다.

+0

URL의 특정 패턴에 대해 작동하므로 모든 유형의 URL에 대해 정규 표현식을 제안하십시오. –

+0

두 번째 경우에는 https://example.com/search를 \ 1로 바꿔주세요. 첫 번째 경우에는 안됩니다. – sergio0983