2010-12-22 5 views
1

임 퀴즈 시스템을 개발 PHP에서 대체 ..문자열</p> <p>하자 내가이 문자열을 가지고 있다고 ..

$my_string = "The language i use is [ans]php[/ans]"; 

출력은 다음과 같습니다

내가 사용하는 언어는 [입력 이름 = 'ans'id = 'ans'/] // 방식으로 텍스트 상자

나는 preg_replace 함수를 사용하지만 행운은 사용하지 않습니다.

내 코드 :

$string = 'The quick [j]brown[/j] fox jumped over the lazy dog.'; 
$patterns = array(); 
$patterns[0] = '!\[j\]]'; 
$patterns[1] = '/brown/'; 
$patterns[2] = '\[/j\]!'; 
$replacements = array(); 
$replacements[0] = ''; 
$replacements[1] = '<input type="text" name="j_1" id="j_1" />'; 
$replacements[2] = ''; 
echo preg_replace($patterns, $replacements, $string); 

출력했다 :

The quick []<input type="text" name="j_1" id="j_1" /> [/] fox jumped over the lazy dog. 

기대 : 너희들이 도울 수 있다면

The quick <input type="text" name="j_1" id="j_1" /> fox jumped over the lazy dog. 

정말 감사 ..

감사

+2

정말로 출력하고 싶습니까? – alexn

+1

무엇이 잘못되었는지 알아 내려고 코드를 게시 해주세요 ... – ircmaxell

+0

출력이 달라졌습니다 ... – zacual

답변

0

이것은 설명대로 작동합니다. 위의 예에 대한 대체 문자열에서 $1을 사용하여
$string = preg_replace('/\[j\](.*)\[\/j\]/', '<input type="text" name="j_1" id="j_1" />', $string);
print $string;

또한 태그 사이에 대체 무엇이든지 액세스 할 수 있습니다

$string = 'The quick [j]brown[/j] fox jumped over the lazy dog.';

. 당신이 대답해야한다 무엇을 잡기 위해 다른 preg_replace이다를 실행하고 싶었다면

, 당신은 같은 것을 할 것입니다 :

$string = 'The quick [j]brown[/j] fox jumped over the lazy dog.';
$answer = preg_replace('/(.*)\[j\](.*)\[\/j\](.*)/', '$2', $answer);
print $answer;

이유를 당신은 그것의 때문에 $2가 사용 문자열의 두 번째 일치 (. 세 (.*), 그 경기의 각 뭔가 그래서이 얼마나, $1The quick, $2brown 동일 것 같을 것이며, $3fox jumped over the lazy dog. 동일 할 확인할 수 있습니다.)

+0

고마워요. – zacual

0
$my_string = "The language i use is [ans]php[/ans] and bla bla [o]php[/o]"; 
$my_html = preg_replace('/\[(.*?)\].*?\[\/.*?\]/msi','<input id="$1" name="$1"/>',$my_string); 
echo $my_html; 
0

이 시도 :

$my_string = preg_replace('#\[(.*?)\](.*?)\[/\1\]#', 
          '<input type="text" name="\1_1" id="\1_1" />' 
          ,$my_string); 

See it

관련 문제