如何删除除了PHP中某些部分之外的字符串中的所有内容?

如何删除除了PHP中某些部分之外的字符串中的所有内容?

问题描述:

Let's say I have string like this:

Village_name(315|431 K64)

What I want to do is when I paste that into let's say text box, and click a button, all I will be left with is 315|431.

Is there a way of doing this?

假设我有这样的字符串: p>

  Village_name(  315 | 431 K64)
  code>  pre> 
 
 

我想要做的是当我将其粘贴到let的说文本框中,然后单击一个按钮,我将留下的是 315 | 431 code>。 p>

有没有办法做到这一点? p> div>

Please try this:-

<?php

   $str = 'Village_name(315|431 K64)';
   preg_match_all('/(?:\d+\|\d+)/', $str, $matches);
   echo "<pre/>";print_r($matches);//print in array format completly
   $i=0;
   foreach($matches as $match){ //iteration through one foreach as you asked
       echo $match[$i];
      $i++;
   }
?>

Output:- http://prntscr.com/74ddg9

Note:- explode can work with some adjustment but if the format only like what you given.So go for preg_match_all. It's best.

Use the below regex and then replace the match with \1.

(\d+\|\d+)|.

It captures the number|number part and matches all the remaining chars. By replacing all the matched chars with \1 will give you the number|number part only.

DEMO

In php, you may use this also.

(?:\d+\|\d+)(*SKIP)(*F)|.

substring which was matched by \d+\|\d+ regex would be matched first and the following (*SKIP)(*F) makes the regex to fail. Now thw . after the pipe symbol would match all the chars except number|number because we already skipped that part.

DEMO

I know this question has been answered and the answer has been accepted. But I still want to suggest this answer, as you really don't need to use PHP to realize your requirement. Just use Javascript. Its enough:

var str = 'Village_name(315|431 K64)';
var pattern = /\((\w+\|\w+) /;
var res = str.match(pattern);
document.write(res[1]);