在X出现特定单词

时间:2016-10-12 13:45:33

标签: php

如何根据更改的计数选择字符串的内容?每次循环运行时,计数增加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等的参考页面,但我还没有看到一种允许触发词位置根据递增计数器改变的方法。

3 个答案:

答案 0 :(得分:2)

可以使用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

答案 1 :(得分:0)

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

$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

答案 2 :(得分:0)

我找到了解决方案,虽然它可能不是最干净或最好的方式,但确实有效。  $ 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.")";
}