回答編集履歴

2

すみません…置換なの見落として検索だと思って回答していたので処理変更しました

2016/12/24 16:27

投稿

momosan
momosan

スコア176

test CHANGED
@@ -1,4 +1,4 @@
1
- preg_matchを使用してみてはいかがでしょうか
1
+ preg_replaceを使用してみてはいかがでしょうか
2
2
 
3
3
  正規表現を使うので少しややこしいですが、覚えておくと何かと便利かと思います。
4
4
 
@@ -14,29 +14,17 @@
14
14
 
15
15
  $pettern = '/あ(.+)お/u';
16
16
 
17
- echo match_result($pettern, $str_1) . PHP_EOL;
17
+ $word = "NG";
18
18
 
19
- echo match_result($pettern, $str_2) . PHP_EOL;
19
+ echo preg_replace($pettern, $word, $str_1) . PHP_EOL;
20
20
 
21
+ echo preg_replace($pettern, $word, $str_2) . PHP_EOL;
22
+
21
- echo match_result($pettern, $str_3) . PHP_EOL;
23
+ echo preg_replace($pettern, $word, $str_3) . PHP_EOL;
22
24
 
23
25
 
24
26
 
25
- function match_result($pettern, $str){
26
-
27
- if(preg_match($pettern, $str)){
28
-
29
- return "NG";
30
-
31
- }
32
-
33
- return $str;
34
-
35
- }
36
-
37
27
  ```
38
-
39
- こんな感じ?(パッと書いたので参考程度に;)
40
28
 
41
29
  また、日本語で正規表現を使う場合は上記のように「/u」が必要です。
42
30
 
@@ -44,9 +32,9 @@
44
32
 
45
33
  ■参考
46
34
 
47
- preg_match
35
+ preg_replace
48
36
 
49
- http://php.net/manual/ja/function.preg-match.php
37
+ http://php.net/manual/ja/function.preg-replace.php
50
38
 
51
39
  日本語の正規表現を使う場合
52
40
 
@@ -54,10 +42,8 @@
54
42
 
55
43
 
56
44
 
57
- それとstr_replaceは置換に使用する関数なので今回は使用しなそうです。
58
-
59
45
  今回は「あ・・・お」のような検索方法だったので正規表現を提案しましたが、
60
46
 
61
47
  もし「あいうえお」の中の「あいう」等のかたまりの文字列を検索したい場合は
62
48
 
63
- 正規表現を使用しないstrpos,mb_strposを使用すると楽かなと思います。
49
+ 正規表現を使用しないstr_replaceを使用すると楽かなと思います。

1

str_replaceについて追加

2016/12/24 16:27

投稿

momosan
momosan

スコア176

test CHANGED
@@ -42,6 +42,8 @@
42
42
 
43
43
 
44
44
 
45
+ ■参考
46
+
45
47
  preg_match
46
48
 
47
49
  http://php.net/manual/ja/function.preg-match.php
@@ -49,3 +51,13 @@
49
51
  日本語の正規表現を使う場合
50
52
 
51
53
  http://codaholic.org/?p=1671
54
+
55
+
56
+
57
+ それとstr_replaceは置換に使用する関数なので今回は使用しなそうです。
58
+
59
+ 今回は「あ・・・お」のような検索方法だったので正規表現を提案しましたが、
60
+
61
+ もし「あいうえお」の中の「あいう」等のかたまりの文字列を検索したい場合は
62
+
63
+ 正規表現を使用しないstrpos,mb_strposを使用すると楽かなと思います。