【问题标题】:How to Get the word of a string from select area php如何从选择区域php中获取字符串的单词
【发布时间】:2018-01-02 11:24:35
【问题描述】:

我有三个字。但我只需要{}中的那些词 喜欢:

text1 {text2} text3

仅获取 { } 中的文本

Result = text2
And
result = text1 text3 (remove {} word )
and
from text1 {text2} text3 {text4}
result = text2 and text4

【问题讨论】:

标签: php


【解决方案1】:

为此尝试preg_match_all

$a = 'text1 {text2} text3';
 preg_match_all("/\\{(.*?)\\}/", $a, $matches); 
print_R($matches[1][0]);

输出将是:

text2

【讨论】:

  • 我还需要两个结果 result = text1 text3 (remove {} word ) 和来自 text1 {text2} text3 {text4} result = text2 and text4
  • @AshikKaiser 检查$matches 数组以获取$a = 'text1 {text2} {text3}'; 它将返回'数组([0] => 数组([0] => {text2} [1] => {text3}) [1] => 数组 ([0] => text2 [1] => text3) )'
【解决方案2】:

一种解决方案是遍历每个字符。 如果字符是 { 然后开始将字符收集到 word 变量中。 如果你找到 } 字符,然后完成 - 你有一个单词。

【讨论】:

  • preg_match 或 preg_match_all 更好。内存消耗更少,因此速度更快。
  • 如果内存和速度是问题,那么是的。否则,对我来说,可读性更重要。
【解决方案3】:

使用正则表达式:

$search = 'text1 {text2} text3';
preg_match('#\{(.*)\}#', $search, $match);
echo $match[1];

preg_match文档

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-25
    • 1970-01-01
    • 1970-01-01
    • 2010-09-20
    • 1970-01-01
    • 1970-01-01
    • 2018-04-10
    相关资源
    最近更新 更多