PHP:如何从前两次出现的字符中获取字符串

PHP:如何从前两次出现的字符中获取字符串

问题描述:

So let's say that I have the following code:

$var = '-77-randomtext-moretext.extension'

So that nothing in the variable is fixed, except for the hyphens ( - ), and the extension.

Then let's say that I need to strore the '-77-' part as a string. '-77-' meaning anything in between the first two hyphens, including the hyphens themselves.

How could I do this?

所以我要说我有以下代码: p>

   $ var ='-77-randomtext-moretext.extension'
  code>  pre> 
 
 

除了连字符( - )和扩展名外,变量中没有任何内容是固定的 。 p>

然后让我说我需要将'-77-'部分作为一个字符串。 '-77-'表示前两个连字符之间的任何内容,包括连字符 他们自己。 p>

我怎么能这样做? p> div>

The two primary ways to do that would be either explode or preg_filter.

Split:

$varArray = explode( '-', $var );
$string77 = '-' . $varArray[1] . '-'; // equals '-77-'

preg_filter;

$string77 = preg_filter( '/^(-.+-).*$/', '$1', $varArray ); // equals '-77-', or NULL if the string doesn't match

The split method is quicker, but less reliable. preg_filter will ensure you always get either the data you want, or a NULL if it doesn't exist, but requires more processing.

You could use:

$parts = explode('-', $var);
$txt = '-' . $parts[1] . '-';

Use the distance between two strpos() calls and get the substr() based on those positions:

$var = '-77-randomtext-moretext.extension';
$first_pos = strpos($var,'-');

$second_pos = strpos($var,'-',($first_pos+1)); //we offset so we find the second 
$length = ($second_pos+1) - $first_pos; //get the length of the string between these points
echo  substr($var,$first_pos,$length); 

You could also use a regex expression (preg_match()) or use the explode() approach:

$pieces = explode('-',$var);
$results = '-'.$pieces[0].'-';

But this only works if you know that the first and second delimiter will be the same.

You could use a regular expression: /-(.+?)-/

$var = '-77-randomtext-moretext.extension';
preg_match('/-(.+?)-/', $var, $matches);
echo $matches[0]; // -77-