4

I have the following phrase and I need in PHP to remove the English Characters

$field = "日本語フレーズ A Japanese phrase A Japanese phrase 日本語フレーズ";

I have the following regular expression

trim(preg_replace('/[a-zA-Z]/', '', $field));

but this will leave with more than a single space between.

日本語フレーズ       日本語フレーズ

I need to have only one space between them. The following is the expected output.

日本語フレーズ 日本語フレーズ
gmponos
  • 2,157
  • 4
  • 22
  • 33
  • What's your expected output? did you want to remove japanese chars or english alpha? – Avinash Raj Jul 06 '15 at 06:05
  • would just add optional amount of spaces after each en-word and replace with empty `$str = preg_replace('/[a-z]+ */ui', "", $str);` [see eval.in](https://eval.in/393160) - yours left spaces, because you didn't target any spaces. – Jonny 5 Jul 06 '15 at 07:15

4 Answers4

3
[a-zA-Z ]+

You can try this.Replace by .See demo.

https://regex101.com/r/cK4iV0/16

$re = "/[a-zA-Z ]+/m";  
$str = "日本語フレーズ A Japanese phrase A Japanese phrase 日本語フレーズ"; 
$subst = " "; 

$result = preg_replace($re, $subst, $str);
vks
  • 67,027
  • 10
  • 91
  • 124
  • Delimiter must not be alphanumeric or backslash – splash58 Jul 06 '15 at 06:24
  • @MponosGeorge you can do it in one regex – vks Jul 06 '15 at 06:25
  • Ok. I would do the same, so pay attention – splash58 Jul 06 '15 at 06:26
  • `*`jealously`*` see you got the regex goldmedal already :] – Jonny 5 Jul 06 '15 at 08:55
  • @Jonny5 long time!!!!!!! goldmedal :P...............if you were as acitve as i am on SO ...u would have got it twice :P – vks Jul 06 '15 at 08:57
  • This answer is incorrect. Because it replaces the pattern with space. I don't want to replace the pattern with space. What if the string that I have has no spaces? It would end up with a space. So for example if the string was `日本語フレーズJAPAN日本語フレーズ` I would end up with an unnecessary space. 日本語フレーズ 日本語フレーズ https://regex101.com/r/cK4iV0/20 – gmponos Jul 06 '15 at 11:56
2

You need to try something like this:-

<?php
$field = "日本語フレーズ A Japanese phrase A Japanese phrase 日本語フレーズ";
$field1 = trim(preg_replace('/[a-zA-Z]/', ' ', $field));
echo trim(preg_replace('/\s+/', ' ', $field1));
?>
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
  • I have to admit that another answer was more valid although more complex. Your case has an issue on the 2nd line where it replaces the string with space. So in some cases if the English word has no spaces `日本語フレーズJAPAN日本語フレーズ` I will end up with an unnecessary space. – gmponos Jul 06 '15 at 12:05
1

You need to add another preg_replace function.

$str = preg_replace(/[A-Za-z]/, '', $field);
echo preg_replace(/^\h+|\h+$|(\h)+/, '\1', $str);
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
0

Try this:

trim(preg_replace('/[a-zA-Z ]/', ' ', $field));
Daniel
  • 350
  • 4
  • 12