Search inside a string

梦想与她 提交于 2019-12-24 10:23:43

问题


$variable = 'of course it is unnecessary [http://google.com], 
but it is simple["very simple"], and this simple question clearly
needs a simple, understandable answer [(where is it?)] in plain English'

Value of this variable everytime changes.

What I trying to do is to get the text from [...]. So, if there is [(google)], the match should be (google).

I'm searching for a solution, which can do each of these actions:

  1. get all matches of [...], write into $all
  2. get only the first match, write into $first
  3. get only the last match, write into $last
  4. remove all matches of [...] from the variable (erase)
  5. remove only first match
  6. remove only last match

Tried different regex for this, like /[\(.*?\)]/, but the results aren't what one might expect.


回答1:


This should do it:

$variable = 'of course it is unnecessary [http://google.com], 
but it is simple["very simple"], and this simple question clearly
needs a simple, understandable answer [(where is it?)] in plain English';

preg_match_all("/(\[(.*?)\])/", $variable, $matches);

$first = reset($matches[2]);
$last = end($matches[2]);
$all = $matches[2];

# To remove all matches
foreach($matches[1] as $key => $value) {
    $variable = str_replace($value, '', $variable);
}

# To remove first match
$variable = str_replace($first, '', $variable);

# To remove last match
$variable = str_replace($last, '', $variable);

Note that if you use str_replace to replace the tags, all similar occurences of the tags will be removed if such exist, not just the first.



来源:https://stackoverflow.com/questions/3734519/search-inside-a-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!