PHP查找字符串只知道它的开头

时间:2018-04-15 10:37:15

标签: php

你好我试图找到其余的字符串只知道它的开头。

实施例: 我有字符串Dude=99999的开头 数字99999的变化并不总是相同,但单词Dude始终是相同的。 所以我的问题是如何在单词Dude...之后找到字符串的其余部分 我知道在linux中有类似t*.txt但有php的内容?求助。

简短:找到'dude=并阅读字符串,直到'

3 个答案:

答案 0 :(得分:1)

这听起来像正则表达式的匹配:

$regex = "/\'Dude=([0-9]+)\'/";
$str = "'Duck=123456' 'Chicken=982731' 'Dude=123487' 'Boat=129832'";

preg_match_all($regex, $str, $matches, PREG_SET_ORDER, 0);

echo $matches[0][1]; // prints: 123487

如果输入字符串/文本有换行符,则可能需要为正则表达式匹配器添加其他标志。但是已经有问题和答案,所以请参考搜索。

答案 1 :(得分:0)

您应该为此

使用“str_replace()”函数
echo str_replace("dude=","","dude=99999");

这里的第一个参数是你的修复字符串,它将如上所述,第二个参数是替换字符串,它被置为空,第三个参数是你的实际字符串

答案 2 :(得分:0)

如果您要检查所有不同字符串的行,您可以像我最近所做的那样:

// loop through all uploaded files:
for ($key = 0; $key < count($_FILES['file']['tmp_name']); $key++) {

  // make an array of lines from a single file:
  $txt_file = file($_FILES['file']['tmp_name'][$key]);

  // loop through this array, line by line:
  foreach ($txt_file as $line) {

    // if your file is not utf-8 fix the encoding:
    $line = iconv("windows-1251", "utf-8", $line);

    // check if this string begins with 'Dude=':
    if (substr($line, 0, strlen('Dude=')) === 'Dude=') {

      // if yes, then trim the 'Dude=' and get what's after it:
      $found_value[$key]['dude'] = trim(substr($line, strlen('Dude=')));

      // if this string begins with 'Dude=' it cannot begin with something else,
      // so we can go straight to the next cycle of the foreach loop:
      continue;

      // check if this string begins with 'Something else=':
    } elseif (substr($line, 0, strlen('SomethingElse=')) === 'SomethingElse=') {

      // if yes, then trim the 'SomethingElse=' and get what's after if:
      $found_value[$key]['something_else'] = trim(substr($line, strlen('SomethingElse=')));

      // if there's more items to find in the string use 'continue' to shorten server's work
      continue;
    }
  }
}

我已经适应并为你评论了它。您也可能想检查文件是否已正确上传,因此您可以使用file_existsis_uploaded_file

最后,您将得到一个结构如下的数组:

$found_value [
  1 => array()[
    'dude' => 9999999
    'something_else' => 'hello'
  ]
  2 => array()[
    'dude' => 3765234
    'something_else' => 'hello again'
  ]
]