質問するログイン新規登録

回答編集履歴

1

2015/02/05 03:12

投稿

hogehogehoge
hogehogehoge

スコア165

answer CHANGED
@@ -2,7 +2,6 @@
2
2
 
3
3
  まず1つ目が、preg_grep()関数を使った方法です。コード例と出力結果は下記になります。
4
4
 
5
- ```lang-<ここに言語を入力>
6
5
  $search_word = array (
7
6
  'hoge hello',
8
7
  'hello test',
@@ -19,14 +18,12 @@
19
18
  [1] => hello test
20
19
  [2] => hello world
21
20
  )
22
- ```
23
21
 
24
22
  preg_grep()関数の詳しい説明は、PHPマニュアルを参照して下さい。
25
- [http://www.php.net/manual/ja/function.preg-grep.php](http://www.php.net/manual/ja/function.preg-grep.php)
23
+ http://www.php.net/manual/ja/function.preg-grep.php
26
24
 
27
25
  次に2つ目が、preg_match()関数とarray_reduce()関数を使う方法です。コード例と出力結果は下記になります。
28
26
 
29
- ```lang-<ここに言語を入力>
30
27
  $search_word = array (
31
28
  'hoge hello',
32
29
  'hello test',
@@ -35,11 +32,11 @@
35
32
  );
36
33
 
37
34
  function _matchewords($m, $str){
38
- if(preg_match('/^hello (\w+)/i', $str, $matches)){
35
+ if(preg_match('/^hello (\w+)/i', $str, $matches)){
39
- $m[] = $matches[1];
36
+ $m[] = $matches[1];
40
- }
41
- return $m;
42
37
  }
38
+ return $m;
39
+ }
43
40
 
44
41
  $matches = array_reduce($search_word, '_matchewords', array());
45
42
 
@@ -50,22 +47,19 @@
50
47
  [0] => test
51
48
  [1] => world
52
49
  )
53
- ```
54
50
 
55
51
  preg_match()関数とarray_reduce()関数の詳しい説明は、PHPマニュアルを参照して下さい。
56
- [http://www.php.net/manual/ja/function.preg-match.php](http://www.php.net/manual/ja/function.preg-match.php)
52
+ http://www.php.net/manual/ja/function.preg-match.php
57
- [http://www.php.net/manual/ja/function.array-reduce.php](http://www.php.net/manual/ja/function.array-reduce.php)
53
+ http://www.php.net/manual/ja/function.array-reduce.php
58
54
 
59
55
  最後に3つ目が、既存のarray_*やpreg_*関数を使わない簡単な方法です。コード例は下記になります。
60
56
 
61
- ```lang-<ここに言語を入力>
62
57
  $matches = array ();
63
58
 
64
59
  foreach ($search_word as $str){
65
- if (preg_match('/^hello (\w+)/i', $str, $m)){
60
+ if (preg_match('/^hello (\w+)/i', $str, $m)){
66
- $matches[] = $m[1];
61
+ $matches[] = $m[1];
67
- }
68
62
  }
69
- ```
63
+ }
70
64
 
71
65
  おそらくこれらの方法で検索できると思います。