2017-04-04 10 views
3

정의를 표현하는 모든 단어 주위에 따옴표를 넣고 싶습니다. 모든 단어는 후행 콜론에 의해 그렇게해야합니다. 예를 들어모든 단어 주위에 따옴표를 붙이고 콜론을 붙이는 정규식

:

def1: "some explanation" 
def2: "other explanation" 

는 내가 PHP에서 preg_replace이다 이것을 쓰기 어떻게

"def1": "some explanation" 
"def2": "other explanation" 

로 변환해야합니까?

나는이있다 :

preg_replace('/\b:/i', '"$0"', 'def1: "some explanation"') 

을하지만 그것은뿐만 아니라 단어, 콜론 enquotes : 난 당신을 대체했습니다

preg_replace('/([^:]*):/i', '"$1" :', 'def1: "some explanation"'); 

: 여기

key":" "value" 
+0

도움이되면 답을 표시하는 것을 잊지 마세요 :) – kaldoran

+0

내 대답을 참조하십시오. 모든 출현을 대체하는 데 도움이 될 수 있습니다. –

답변

5

는 솔루션입니다 정규 표현식 [^:]*: a를 제외한 모든 문자를 의미합니다. 그런 다음 ()을 사용하여 얻습니다. 이는 $1입니다. 그런 다음 $1을 따옴표로 다시 쓰고 제거 된 :을 추가하십시오.

편집 : 각 줄마다 반복하고 preg_replace를 적용하면 트릭을 수행합니다.

http://ideone.com/9qp8Hv

+1

하나의 항목에서만 작동하고 동일한 줄에 항목을 추가하고 다시 테스트하십시오. :) https://eval.in/767366 및 https://eval.in/767370 – Fky

+0

그냥 각 줄에 적용해야 함) – kaldoran

+0

동의하지만 지정해야합니다.) – Fky

0

당신이 예에 표시로 패턴은 항상 같은 등이 될 경우, 즉 3 문자 1 자리 (등등 즉 def1, def2, DEF3 등) 다음 패턴 아래에 사용할 수 있습니다

echo preg_replace('/\w+\d{1}/', '"$0"', 'def1: "some explanation" def2: "other explanation"'); 

출력 :

"def1": "some explanation" "def2": "other explanation" 

숫자 나 문자 가질 수있는 다른 해결책 :

echo preg_replace('/\w+(?=:)/', '"$0"', 'def1: "some explanation" def2: "other explanation" def3: "other explanation" defz: "other explanation"'); 

출력 : 위의 솔루션의

"def1": "some explanation" "def2": "other explanation" "def3": "other explanation" "defz": "other explanation" 

Explaination : 두 솔루션 모두 occurance를 대체 할

\w Word. Matches any word character (alphanumeric & underscore). 
+ Plus. Match 1 or more of the preceding token. 
(?= Positive lookahead. Matches a group after the main expression without including it in the result. 
: Character. Matches a ":" character (char code 58). 
) 

.