php - 从字符串中获取特定字符串?

标签 php

我一直在尝试从字符串中获取特定的字符串,例如从下面的这个字符串中

Scale Lengths

4 string model - E A D G
5 string model - B E A D G
6 string model - B E A D G C

B   37″

我想要这部分

4 string model - E A D G
5 string model - B E A D G
6 string model - B E A D G C

我的代码如下,我得到了正确的答案

<?php
$str = 'Scale Lengths

4 string model - E A D G
5 string model - B E A D G
6 string model - B E A D G C

B
37″';

echo getBetween($str,'Scale Lengths','37″');
function getBetween($content,$start,$end){
  $r = explode($start, $content);
  if (isset($r[1])){
      $r = explode($end, $r[1]);
      return $r[0];
  }
  return '';
}
 ?>

问题: 我的问题是我上面的代码只针对这个字符串的静态类型。例如,如果我们将 37″ 更改为 28″ 或将此数字之前的 B 更改为 C 它将开始给出错误的答案。

最佳答案

尝试像这样更改您的代码:

<?php
$str = 'Scale Lengths

4 string model - E A D G
5 string model - B E A D G
6 string model - B E A D G C

B
37″';

$get_occurence=explode(" ",$str);
$split=preg_replace('/\s+/', '', end($get_occurence));
$split=preg_replace('/^[a-zA-Z]+/', '', $split);
$getBetween=getBetween($str,'Scale Lengths',$split);
$getLength=strlen($getBetween);
$getString=substr($getBetween,0,$getLength-3);

echo $getString;
function getBetween($content,$start,$end){
$r = explode($start, $content);
if (isset($r[1])){
  $r = explode($end, $r[1]);
  return $r[0];
}
return '';
}


?>

我已经编辑了一些代码,所以你可以用任何你想要的动态替换 B 字符串。

<?php
$str = 'Scale Lengths

4 string model - E A D G
5 string model - B E A D G
6 string model - B E A D G C

B
37″';

$get_occurence=explode(" ",$str);
$split=preg_replace('/\s+/', '', end($get_occurence));
$split=preg_replace('/^[a-zA-Z]+/', '', $split);
$split_integer=preg_replace('/\s+/', '', end($get_occurence));
$split_integer=preg_replace('/[^a-zA-Z.]*/', '', $split_integer);
$getBetween=getBetween($str,'Scale Lengths',$split);
$getLength=strlen($getBetween);

$getString=substr($getBetween,0,$getLength-(strlen($split_integer)+1));

echo $getString;
function getBetween($content,$start,$end){
$r = explode($start, $content);
if (isset($r[1])){
  $r = explode($end, $r[1]);
  return $r[0];
}
return '';
}


?>

希望对你有帮助。

关于php - 从字符串中获取特定字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53809127/

相关文章:

php 循环跳过或缺少 mysql 查询的某些结果

php - 数据库连接错误(1) : The MySQL adapter 'mysql' is not available

php - 引用:什么是变量作用域?哪些变量可从何处访问?什么是“ undefined variable ”错误?

php 大于特定时间

php - mongo 搜索大量 mongo id

php - CakePHP 即时切换数据库(使用相同的数据源)?

PHP 设置日期 ('w' ) 函数将星期日返回为 7,而不是 0

php - 如何合并这两个SQL查询?

PHP mysqli 用逗号一起插入而不是一一插入

php - MYSQL为200行生成5个随机字符(1-9,A-Z)