2012-03-25 4 views
1

저는 twitters와 비슷한 회신 시스템을 만들고 있습니다.
문자열에는 ID가 변수 인 텍스트 조각이 있습니다. 답장하는 사람에 따라 14&, 138&이 있습니다.
문자열에서 14&을 찾고 <u>14&</u>으로 바꾸려면 어떻게해야합니까?정확한 변수 문자열을 PHP의 변수 텍스트로 바꾸시겠습니까?

이 보이는 방법입니다

<u>14&</u> this is a reply to the comment with id 14 

이 어떻게 PHP에서이 작업을 수행 할 수 있습니다

14& this is a reply to the comment with id 14 

이 그것을 같이하는 방법입니까? 미리 감사드립니다! 당신이 ID를 알고있는 경우

+0

공간, 임의의 크기 및 번호는 다음 공간 - 맞습니까? –

+0

@ 대진 예, 맞습니다. :) –

+0

다음에서 3과 4를 대체 하시겠습니까? 아니면 제외해야합니까? 처음에는 '1'입니다. 2 & 중간에. 3 단어 뒤에. And4 & 단어가 선행되었습니다. 마지막으로 5 &'? –

답변

2
$text = "14& this is a reply to the comment with id 14"; 

var_dump(preg_replace("~\d+&~", '<u>$0</u>', $text)); 

출력 :

string '<u>14&</u> this is a reply to the comment with id 14' (length=52) 

& 제거하려면 :

preg_replace("~(\d+)&~", '<u>$1</u>', $text) 

출력 :

string '<u>14</u> this is a reply to the comment with id 14' (length=51) 

$0 또는 $1이 될 것입니다 너의 이드. 마크 업을 원하는대로 바꿀 수 있습니다. 예컨대

링크 :

$text = "14& is a reply to the comment with id 14"; 

var_dump(preg_replace("~(\d+)&~", '<a href="#comment$1">this</a>', $text)); 

출력 :

string '<a href="#comment14">this</a> is a reply to the comment with id 14' (length=66) 
+0

을 사용한다. 그것은 트릭을했는데, 고마워! –

2

, 그것은 간단합니다

<?php 
    $tweet_id = '14'; 
    $replaced = str_replace("{$tweet_id}&", "<u>{$tweet_id.}&</u>", $original); 

그렇지 않으면 preg_replace이다 preg_replace 기능

<?php 
    //look for 1+ decimals (0-9) ending with '$' and replaced it with 
    //original wrapped in <u> 
    $replaced = preg_replace('/(\d+&)/', '<u>$1</u>', $original); 
+0

ID를 모르는 경우? –

+0

나는 나의 대답을 확장했다 : 그것은 [preg_replace] (http://php.net/manual/en/function.preg-replace.php) –

2

를 사용하여 정규 표현식.

<?php 

$str = '14& this is a reply to the comment with id 14'; 
echo preg_replace('(\d+&)', '<u>$0</u>', $str); 

정규식이 일치합니다. 하나 이상의 숫자와 그 뒤에 앰퍼샌드가옵니다.