只获取某些字符串(PHP)

时间:2017-12-14 11:41:40

标签: php

文字:

TestString
HT-Child1 CLASS-Class1
AnotherString
HT-Child2 CLASS-Class2
HT-Child3 CLASS-Class3
HT-Child4 CLASS-Class4
CLASSOFWEEK-Class

到目前为止我所拥有的:(内部$display->getExtraHTML()是文本)。有人可以指导我做我需要做的事情来调整我的代码以获得我想要的结果。

<?php 
    $additionalHTML = explode("\n", $display->getExtraHTML());
    $html = "";
    $html .= "<ul>";
        foreach($additionalHTML as $key => $item){
            $html .= "<li>$item</li>";
        }
    $html .= "</ul>";
    echo $html;
?>

我知道我可以使用这样的东西来获取字符串,但是如何使用它来获取我需要的所有值?

$string = strstr($display->getExtraHTML(), "HT-"); // gets all text from HT
$string = strstr($string, "CLASS-", true); // gets all text before CLASS

我可以同时使用explodestrstr到达我想要的位置吗?

期待HTML标记:

预期结果:(获取HT-CLASS-

的值
<ul>
   <li>Child1 Class1</li>
   <li>Child2 Class2</li>
   <li>Child3 Class3</li>
   <li>Child4 Class4</li>
</ul>

3 个答案:

答案 0 :(得分:1)

这是解决方案

 <?php
$str = "TestString
HT-Child1 CLASS-Class1
AnotherString
HT-Child2 CLASS-Class2
HT-Child3 CLASS-Class3
HT-Child4 CLASS-Class4
CLASSOFWEEK-Class";



    $additionalHTML = explode("\n", $str);
    $html = "";
    $html .= "<ul>";
        foreach($additionalHTML as $key => $item){
          if(substr($item,0,3) == "HT-") {
            $i = explode(" ",$item);
            $a = substr($i[0],3);
            $b = substr($i[1],6);
            $html .= "<li>$a"." ". "$b</li>";
          }
        }
    $html .= "</ul>";
    echo $html;

结果

Child1 Class1
Child2 Class2
Child3 Class3
Child4 Class4

答案 1 :(得分:1)

使用preg_match_all函数的完整解决方案:

$txt = '
TestString
HT-Child1 CLASS-Class1
AnotherString
HT-Child2 CLASS-Class2
HT-Child3 CLASS-Class3
HT-Child4 CLASS-Class4
CLASSOFWEEK-Class';

preg_match_all('/^HT-(\S+)\s+CLASS-(\S+)/m', $txt, $m);
$html = "<ul>";
if (isset($m[1]) && isset($m[2])){
    foreach(array_map(null, $m[1], $m[2]) as $pair){
        $html .= "<li>". implode(' ', $pair) ."</li>";
    }
}

$html .= "</ul>";
echo $html;

输出(推送运行代码段):

&#13;
&#13;
<ul><li>Child1 Class1</li><li>Child2 Class2</li><li>Child3 Class3</li><li>Child4 Class4</li></ul>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您可以使用正则表达式来查找匹配的行并提取所需的数据:

# Unfortunately, macOS's devfs is based on the old FreeBSD
# one, not the current one, so there's no way to configure it
# to create BPF devices with particular owners or groups. BPF
# devices on macOS are also non-cloning, that is they can
# be created on demand at any time. This startup item will
# pre-create a number of BPF devices, then make them owned by
# the access_bpf group, with permissions rw-rw----, so that
# anybody in the access_bpf group can use programs that capture
# or send raw packets.