【问题标题】:How to split in between a string in PHP?如何在PHP中的字符串之间拆分?
【发布时间】:2014-03-07 17:45:43
【问题描述】:

我在一个文本文件中有以下字符串:

^b^B

我正在尝试将其拆分为两个变量。我当前的代码使用的是explode(),但它不能按我的意愿工作:

$num1 = '^b';
$num2 = '^B';

我怎样才能使用 PHP 来完成这项工作?

这是我的密码

<?php 
if(isset($_POST['refresh'])) {
exec('/var/www/www.rfteste.com/htdocs/estado.sh');
}
if(isset($_POST['on'])) {
exec('/var/www/www.rfteste.com/htdocs/on.sh');
}
if(isset($_POST['off'])) {
exec('/var/www/www.rfteste.com/htdocs/off.sh');
}
echo "<H3>CONTROL PANEL</H3>";
$str = file_get_contents("/var/www/www.rfteste.com/htdocs/refresh.txt");
$vals = explode("^", $str);
$num1 = "^".$vals[0];
$num2 = "^".$vals[1];
$onoff= "^A";
if($num2 == $onoff)
echo "<b>on</b>";
else
echo "<b>off</b>";
?>
<html>
<body>
<form method="post" action="">
<p>
<center><input type="submit" value="on" name="on""';" /></center>
<center><input type="submit" value="off" name="off""';" /></center>
<center><input type="submit" value="refresh" name="refresh""';" /></center>

【问题讨论】:

  • @Andrea 他做到了,但我不明白为什么在编辑后他的尝试被他或其他用户消失了
  • @Naeem:它已被 OP 本身删除。有关详细信息,请参阅revision history
  • 我觉得这个问题有点不清楚。编码尝试无助于改善这一点。字母是否重要或插入符号是否重要或两者都重要。这些输入值将如何变化?他们总是4个字符吗?你能把字符串分成两半吗?还是有其他需要尊重的逻辑?
  • 这段代码中的 $num1 和 $num2 得到了什么?

标签: php string split


【解决方案1】:

使用带有环视断言的preg_split()

list($num1, $num2) = preg_split('/(?<=\^b)/', $str);

尸检:

  • / - 起始分隔符
  • (?&lt;= - 积极向后看的开始(意思是“如果在前面”)
    • \^b - 匹配文字字符 ^b
  • ) - 正面回顾结束
  • / - 结束分隔符

可视化:

简单来说,它的意思是:在前面有 ^b 的地方拆分,并使用 list 构造将数组值分配给变量 $num1$num2

Demo

【讨论】:

    【解决方案2】:

    使用preg_match_all():

    <?php
    $str = '^b^B';
    preg_match_all('/(\^.)/', $str, $matches);
    
    var_dump($matches);
    

    【讨论】:

      【解决方案3】:
      #Pull all of the contents of file, myfile.txt, into variable, $str
      $str = file_get_contents("myfile.txt");
      
      #split up the data in $str, at every instance of '^'. 
      $vals = explode("^", $str);
      #now $vals is an array of strings
      
      #concatenate the "^" back into the strings as they were removed by explode.
      $num1 = "^".$vals[0];
      $num2 = "^".$vals[1];
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-22
      • 1970-01-01
      • 2014-10-19
      • 1970-01-01
      相关资源
      最近更新 更多