如何从PHP的字符串中获取特定的字符串值?

时间:2019-05-21 13:10:10

标签: php string

我必须获取一个字符串中包含“#”的值。

Ex:
$string = '#1234 Lorem ipsum is placeholder text commonly used in the graphic, #rm1345 print, and publishing industries for previewing layouts and visual mockups';

Expected results:
 #1234 and #rm1345

如何从$ string中获得以上结果?

我尝试了以下方法,但对我没有帮助。

$contents = str_word_count($string, 2);
echo 'contents: <pre>';print_r($contents);echo '</pre>';

请帮帮我。

谢谢!

1 个答案:

答案 0 :(得分:2)

在这里输入正则表达式并生成字符串

$string = '#1234 Lorem ipsum is placeholder text commonly used in the graphic, #rm1345 print, and publishing industries for previewing layouts and visual mockups';

$temp = preg_match_all('/(?<!\w)#\w+/', $string, $matches);

echo implode(' and ', $matches[0]);

输出:

#1234 and #rm1345

工作demo

正则表达式测试link。(preg_match_all匹配所有#个附加词)。

来源link

相关问题