【问题标题】:Explode php string on X occurrence of a specific word在特定单词的 X 次出现时分解 php 字符串
【发布时间】:2016-10-12 13:45:32
【问题描述】:

如何根据不断变化的计数选择字符串的内容?每次运行循环时,计数都会增加 1,并且需要字符串的下一部分。

$mystring = 'This is my string. This string is a sample. This is a problem';

所以如果 $i==1 那么我想要

echo $newstring // This is my string.

$i==2 我想要

echo $newstring // This string is a sample.

$i==3 我想要

   echo $newstring // This is a problem.

我查看了很多关于explode、substr、array_pop 等的参考页面,但我还没有看到允许触发词的位置根据递增计数器而改变的方法。

【问题讨论】:

  • 在 PHP 中迭代通常从 0 开始。像其他人回答的那样拆分您的输入是正确的方法。另外,如果您要拆分的单词都是单个字符,请尝试strtok()
  • 如果你的问题有一个真实的例子,你可能会得到更好的答案(需要这个 - 试过这个)。解决方案可能与您假设的算法不同。在您下面的评论中,我看到您的字符串来自 html 并且“单词”实际上是其中的 class 属性。有解析器。
  • @shudder 该字符串实际上是运输方式的数据库条目。在我正在查看的应用程序中,所有 html 内容都是多余的。我只想从最初存储的任何东西中获得“免费送货”、经济送货 (1Kg) 等,但必须能够按照给定的顺序获得它们。

标签: php


【解决方案1】:

可以用Explode a paragraph into sentences in PHP回答这个问题

foreach (preg_split('/[.?!]/',$mystring) as $sentence) {
    echo $sentence;
}

您还可以访问每个元素:

$matches = preg_split('/[.?!]/',$mystring);
echo $matches[0]; // This is my string
echo $matches[1]; // This string is a sample
echo $matches[2]; // This is a problem

【讨论】:

  • 如果 $mystring = 'Shipping (

    免费送货
    1 x IARP,您能否解释一下为什么您的示例不起作用IA313200 门垫

    经济配送 (1Kg)
    1 x WIP69457. Whirlpool 零件编号 481946669457

    )'; $chr = 'AdvancedShipperShippingMethod">'; 我将 '/[.?!]/' 更改为 '/[AdvancedShipperShippingMethod?!]/' echo $matches 什么也没给出
  • 你能告诉我你想要那个字符串的输出是什么吗?
  • 在示例字符串中我想找到 $matches[0]; //免费送货和 $matches[1]; //经济配送(1Kg)
  • 哦,好吧,那你需要把它解析成html,你觉得this answer可以吗?
【解决方案2】:

如果.是你想要分解字符串的部分,那么你可以使用正则表达式。

$line = 'This is my string. This string is a sample. This is a problem.';
preg_match("/([[:alpha:]|\s]+\.)/i", $line, $match);

echo $match[1]; 

示例 https://regex101.com/r/4SHAJj/1

【讨论】:

  • 字符串是纯样本。如果你想在一个特定的词上爆炸怎么办?
  • 是的,你可以这样做。实际上正则表达式在这类事情中非常方便。只是为了向您展示我们可以用正则表达式做什么。在这句话中,我们从句子中删除了国家代码。 regex101.com/r/w6HUsQ/1
  • 这对我来说就像黑魔法!我对所有的 \ 和 / 感到困惑,更不用说 [ ] 中的内容了。如果我想搜索所有出现的 AdvancedShipperShippingMethod 并能够使用 $match[1]、$match[2] 等访问它们,我将如何格式化正则表达式?
【解决方案3】:

我找到了一个解决方案,虽然它可能不是最干净或最好的方法,但它确实有效。 $shippingData 包含

Shipping (<div class="AdvancedShipperShippingMethodCombination"><p class="AdvancedShipperShippingMethod">Free Shipping <br />1 x IARP IA313200 Door Gasket</p> <p class="AdvancedShipperShippingMethod">Economy Delivery (1Kg) <br />1 x WIP69457. Whirlpool Part Number 481946669457</p></div>)';

使用的代码:

$shippingData = $order_result->fields['shipping_method'];
$matches = preg_split("/(AdvancedShipperShippingMethod\">)/", $shippingData);
$method = $matches[$n]; //$n is a count that increments with while/next loop
$method = substr($method, 0, strpos($method, "<br />"));
$method = "Shipping (".$method.")";
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-21
    • 1970-01-01
    • 1970-01-01
    • 2021-04-30
    • 2017-04-29
    • 1970-01-01
    相关资源
    最近更新 更多