문제

내 문자열은 다음과 같습니다

$str = "a quick brown fox over the lazy dog... #fox #dog. hello everybody #lazy";

난 갖길 원해 #fox, #dog 그리고 #lazy 해당 문자열과 다음을 포함하는 모든 단어에서# 이 문자열을 다음과 같은 배열에 추가하고 싶습니다.

 $array = array(
       [0]=>'#fox',
       [1]=>'#dog',
       [2]=>'#lazy',
   );

저 좀 도와주실 분..제발.정말 감사합니다!

도움이 되었습니까?

해결책

이 정규 표현식을 사용할 수 있습니다 '/#(\w+)/'

<?php
$str = "a quick brown fox over the lazy dog... #fox #dog. hello everybody #lazy";
preg_match_all('/#(\w+)/', $str, $matches);
array_walk($matches[1],function (&$v){ $v='#'.$v;});
print_r($matches[1]);

출력 :

Array
(
    [0] => #fox
    [1] => #dog
    [2] => #lazy
)

enter image description here

다른 팁

여기있어:

$s = "a quick brown fox over the lazy dog... #fox #dog. hello everybody #lazy";
$r = array();
preg_match_all('/(?<!\w)#\w+/', $s,$r);
print_r($r);

정규식을 사용하여 preg_match_all 다음으로 시작하는 모든 단어로 구성된 단일 배열을 얻습니다. # 문자열에 포함되어 있습니다.

$str  = "a quick brown fox over the lazy dog... #fox #dog. hello everybody #lazy";
$pattern = '/(?<!\w)#\w+/';
preg_match_all($pattern, $str , $matches);
print_r($matches);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top