Explode php string on X occurrence of a specific word - php

How do you select the content of a string based on a changing count?Each time the loop is run the count increments by 1 and the next portion of the string is required.
$mystring = 'This is my string. This string is a sample. This is a problem';
So if $i==1 then I want
echo $newstring // This is my string.
At $i==2 I want
echo $newstring // This string is a sample.
At $i==3 I want
echo $newstring // This is a problem.
I have looked at lots of reference pages on explode, substr, array_pop etc but I haven't seen a method that allows for the position of the trigger word to change based on an incrementing counter.

This could be answered with Explode a paragraph into sentences in PHP
foreach (preg_split('/[.?!]/',$mystring) as $sentence) {
echo $sentence;
}
Also you can access each element:
$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

If . is the part where you want to explode the string then you can use regular expression.
$line = 'This is my string. This string is a sample. This is a problem.';
preg_match("/([[:alpha:]|\s]+\.)/i", $line, $match);
echo $match[1];
Example
https://regex101.com/r/4SHAJj/1

I found a solution to this, and although it may not be the cleanest or best way, it does work.
$shippingData contains
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>)';
Code used:
$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.")";
}

Related

Replace all the matches in a string that matches array values

I have a string that I am checking for matches using my array and if there are any matches I want to replace those matches with the same words, but just styled red and then return all the string with the colored words included in one piece. This is what I have tried:
$string = 'This is a brovn fox wit legs.';
$misspelledOnes = array('wit', 'brovn');
echo '<p>' . str_replace($misspelledOnes,"<span style='color:red'>". $misspelledOnes . "</span>". '</p>', $string;
But of course this doesn't work, because the second parameter of str_replace() can't be an array. How to overcome this?
The most basic approach would be a foreach loop over the check words:
$string = 'This is a brovn fox wit legs.';
$misspelledOnes = array('wit', 'brovn');
foreach ($misspelledOnes as $check) {
$string = str_replace($check, "<span style='color:red'>$check</span>", $string);
}
echo "<p>$string</p>";
Note that this does a simple substring search. For example, if you spelled "with" properly, it would still get caught by this. Once you get a bit more familiar with PHP, you could look at something using regular expressions which can get around this problem:
$string = 'This is a brovn fox wit legs.';
$misspelledOnes = array('wit', 'brovn');
$check = implode("|", $misspelledOnes);
$string = preg_replace("/\b($check)\b/", "<span style='color:red'>$1</span>", $string);
echo "<p>$string</p>";

Return part of string

I have an array with strings like:
209#ext-local : SIP/209 State:Idle Watchers 2
208#ext-local : SIP/208 State:Unavailable Watchers 1
How can I echo the state for example Idle or Unavailable?
Thanks.
Using regex it will match any string containing letters and numbers.
$string = '209#ext-local : SIP/209 State:Idle Watchers 2';
preg_match("/State\:([A-Za-z0-9]+)/", $string, $results);
echo $results[1]; // Idle
strpos will search the string to see if it is contains the characters in that exact order.
strpos will not always work if the word idle or unavailable has the possibility to show up in any other way in the string.
You can use the php explode and parse the sting into an array of strings.
exp.
$string = "209#ext-local : SIP/209 State:Idle Watchers 2";
$string = explode(':', $string);
will give you ['209#ext-local ',' SIP/209 State','Idle Watchers 2']. Then if you explode the 3rd entry my ' ' you would get your answer.
$answer = explide(' ', $string[2]);
echo $answer[0];
Assuming your strings are all the same format, you can try splitting the string down using explode(), which returns an array of string, separated by a provided delimiter, like
foreach ($yourStrings as $s) {
$colonSplit = explode(":", $stringToSplit);
$nextStringToSplit = $colonSplit[2];
$spaceSplit = explode(" ", $nextStringToSplit);
$status = $spaceSplit[0];
echo $status;
}
May not be elegant but it should work.
Quick (and dirty) way. Assuming your array contains the full elements you listed above, the array element values do NOT contain 'idle' or 'unavailable' in any other capacity other than what you listed, and you just want to echo out the value and "is idle" or "is unavailable":
//$a being your array containing the values you listed above
foreach ($a as $status) {
if (strpos($status, "Idle") == true)
echo $status . " is idle";
elseif (strpos($status, "Unavailable") == true)
echo "$status" . " is unavailable";
}

Find substring that is closest to position needed

I have big string with occurrence needed. And I need to find closest substring to this occurrence.
For example:
<p>one</p><p>two</p><p>three and some more</p><p>four</p><p>five</p>
I am looking for "three", I know it position and I need to get only <p> block with this occurrence.
<p>three and some more</p>
Can I find closest <p> with known position without regexp using?
I think you can explode() your string as an array and the get the known substring position from the array
$string = '<p>one</p><p>two</p><p>three and some more</p><p>four</p><p>five</p>';
$str_array = explode("</p>",$string);
$sub_str = $str_array[2].'</p>';
echo $sub_str;
//output <p>three and some more</p>
Live sample
If i stead you need to find the occurence of the word three
$string = '<p>one</p><p>two</p><p>three and some more</p><p>four</p><p>five</p>';
$str_array = explode("</p>",$string);
foreach($str_array as $value)
{
if(strpos($value,'three'))
{
$sub_str = $value.'</p>';
}
}
echo $sub_str;
//output <p>three and some more</p>
Live sample
Use strpos with a starting index to search after, strrpos to search before.
Edited: strrpos finds the last occurence, so you need to cut the string before.
$s = "<p>one</p><p>two</p><p>three and some more</p><p>four</p><p>five</p>";
$position = strpos($s, "three");
$end_p = strpos($s, "</p>", $position);
$previous_p = strrpos(substr($s, 0, $position), "<p>");
var_dump(substr($s, $previous_p, $end_p - $previous_p + 4));

Increment integer at end of string

I have a string, "Chicago-Illinos1" and I want to add one to the end of it, so it would be "Chicago-Illinos2".
Note: it could also be Chicago-Illinos10 and I want it to go to Chicago-Illinos11 so I can't do substr.
Any suggested solutions?
Complex solutions for a really simple problem...
$str = 'Chicago-Illinos1';
echo $str++; //Chicago-Illinos2
If the string ends with a number, it will increment the number (eg: 'abc123'++ = 'abc124').
If the string ends with a letter, the letter will be incremeted (eg: '123abc'++ = '123abd')
Try this
preg_match("/(.*?)(\d+)$/","Chicago-Illinos1",$matches);
$newstring = $matches[1].($matches[2]+1);
(can't try it now but it should work)
$string = 'Chicago-Illinois1';
preg_match('/^([^\d]+)([\d]*?)$/', $string, $match);
$string = $match[1];
$number = $match[2] + 1;
$string .= $number;
Tested, works.
explode could do the job aswell
<?php
$str="Chicago-Illinos1"; //our original string
$temp=explode("Chicago-Illinos",$str); //making an array of it
$str="Chicago-Illinos".($temp[1]+1); //the text and the number+1
?>
I would use a regular expression to get the number at the end of a string (for Java it would be [0-9]+$), increase it (int number = Integer.parse(yourNumberAsString) + 1), and concatenate with Chicago-Illinos (the rest not matched by the regular expression used for finding the number).
You can use preg_match to accomplish this:
$name = 'Chicago-Illinos10';
preg_match('/(.*?)(\d+)$/', $name, $match);
$base = $match[1];
$num = $match[2]+1;
print $base.$num;
The following will output:
Chicago-Illinos11
However, if it's possible, I'd suggest placing another delimiting character between the text and number. For example, if you placed a pipe, you could simply do an explode and grab the second part of the array. It would be much simpler.
$name = 'Chicago-Illinos|1';
$parts = explode('|', $name);
print $parts[0].($parts[1]+1);
If string length is a concern (thus the misspelling of Illinois), you could switch to the state abbreviations. (i.e. Chicago-IL|1)
$str = 'Chicago-Illinos1';
echo ++$str;
http://php.net/manual/en/language.operators.increment.php

How can we split a sentence

I have written the PHP code for getting some part of a given dynamic sentence, e.g. "this is a test sentence":
substr($sentence,0,12);
I get the output:
this is a te
But i need it stop as a full word instead of splitting a word:
this is a
How can I do that, remembering that $sentence isn't a fixed string (it could be anything)?
use wordwrap
If you're using PHP4, you can simply use split:
$resultArray = split($sentence, " ");
Every element of the array will be one word. Be careful with punctuation though.
explode would be the recommended method in PHP5:
$resultArray = explode(" ", $sentence);
first. use explode on space. Then, count each part + the total assembled string and if it doesn't go over the limit you concat it onto the string with a space.
Try using explode() function.
In your case:
$expl = explode(" ",$sentence);
You'll get your sentence in an array. First word will be $expl[0], second - $expl[1] and so on. To print it out on the screen use:
$n = 10 //words to print
for ($i=0;$i<=$n;$i++) {
print $expl[$i]." ";
}
Create a function that you can re-use at any time. This will look for the last space if the given string's length is greater than the amount of characters you want to trim.
function niceTrim($str, $trimLen) {
$strLen = strlen($str);
if ($strLen > $trimLen) {
$trimStr = substr($str, 0, $trimLen);
return substr($trimStr, 0, strrpos($trimStr, ' '));
}
return $str;
}
$sentence = "this is a test sentence";
echo niceTrim($sentence, 12);
This will print
this is a
as required.
Hope this is the solution you are looking for!
this is just psudo code not php,
char[] sentence="your_sentence";
string new_constructed_sentence="";
string word="";
for(i=0;i<your_limit;i++){
character=sentence[i];
if(character==' ') {new_constructed_sentence+=word;word="";continue}
word+=character;
}
new_constructed_sentence is what you want!!!

Categories