Find substring that is closest to position needed - php

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));

Related

Explode php string on X occurrence of a specific word

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.")";
}

How to find the position of multiple words in a string using strpos() function?

I want to find the position of multiple words in a string.
Forexample :
$str="Learning php is fun!";
I want to get the posion of php and fun .
And my expected output would be :-
1) The word Php was found on 9th position
2) The word fun was found on 16th position.
Here is the code that I tried, but it doesn't work for multiple words.
<?Php
$arr_words=array("fun","php");
$str="Learning php is fun!";
$x=strpos($str,$arr_words);
echo The word $words[1] was found on $x[1] position";
echo The word $words[2] was found on $x[2] position";
Does someone know what's wrong with it and how to fix it?
Any help is greatly appriciated.
Thanks!
To supplement the other answers, you can also use regular expressions:
$str="Learning php is fun!";
if (preg_match_all('/php|fun/', $str, $matches, PREG_OFFSET_CAPTURE)) {
foreach ($matches[0] as $match) {
echo "The word {$match[0]} found on {$match[1]} position\n";
}
}
See also: preg_match_all
Since you can't load an array of string words inside strpos, you could just invoke strpos twice, one for fun and one for php:
$arr_words = array("fun","php");
$str = "Learning php is fun!";
$x[1] = strpos($str,$arr_words[0]);
$x[2] = strpos($str,$arr_words[1]);
echo "The word $arr_words[0] was found on $x[1] position <br/>";
echo "The word $arr_words[1] was found on $x[2] position";
Sample Output
Or loop the word array:
$arr_words = array("fun","php");
$str = "Learning php is fun!";
foreach ($arr_words as $word) {
if(($pos = strpos($str, $word)) !== false) {
echo "The word {$word} was found on {$pos} position <br/>";
}
}
Sample Output
$str="Learning php is fun!";
$data[]= explode(" ",$str);
print_r($data);//that will show you index
foreach($data as $key => $value){
if($value==="fun") echo $key;
if($value==="php") echo $key;
}
Key is the exact position but index start with 0 so keep in mind to modify your code accordingly, may be echo $key+1 (a number of ways, depends on you).
You were doing it in a wrong way check the function
strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )
haystack
The string to search in.
needle
If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.
offset
If specified, search will start this number of characters counted from the beginning of the string.
Refer Docs
Here within your example
$arr_words=array("fun","php");
$str="Learning php is fun!";
$x=strpos($str,$arr_words);
$arr_words is an array not a string or not an integer
so you need to loop it or need to manually pass the key as
$x[1] = strpos($str,$arr_words[0]);
$x[2] = strpos($str,$arr_words[1]);
or
foreach($arr_words as $key => $value){
$position = strpos($str,$value);
echo "The word {$value} was found on {$position}th position"
}
Just another answer:
<?php
$arr_words=array("fun","php");
$str="Learning php is fun!";
foreach($arr_words as $needle) {
$x = strpos($str, $needle);
if($x)
echo "The word '$needle' was found on {$x}th position.<br />";
}
?>
You can not use function strpos if the second params is an array.
This is easiest way:
<?php
$words = array("php","fun");
$str = "Learning php is fun!";
foreach ($words as $word) {
$pos = strpos($str, $word);
// Found this word in that string
if($pos) {
// Show you message here
}
}

PHP adding the value 1 to a position in an string and replace

I want to replace a letter with another character and also add 1 value more.
I mean the values are dynamic
For example I have H9 ,i want to replace as G10 .
Similarly...
H2 as G3
H6 as G7
Is it possible to use str_replace() for this ?
I got this one which works for me:
$old_string = "H2";
$new_string = "G" . (substr($old_string, 1) + 1);
echo $new_string;
Works fine for me. This is just for one value, but i guess you can loop through an array too, just have to modify the values like this
foreach($old_values as $v) {
$new_values[] = "G" . (substr($v, 1) + 1);
}
So you could save all the values into the $new_string array
Try This
<?php
$str = "H25";
preg_match_all('!\d+!', $str, $matches);
$str = str_replace($matches['0']['0'], $matches['0']['0']+1, $str, $count);
echo $str;
?>
Of course you can use str_replace()
Use
$new = array("G10", "G3", "G7");
$old = array("H9", "H2", "H6");
$string = str_replace($old, $new, $string);
where $string is your original string.
More simpler way... (Generalized Solution)
<?php
$str='G10';
preg_match('!\d+!', $str, $digit); //<---- Match the number
$str = substr($str,0,1); //<--- Grab the first char & increment it in the second line
echo ++$str.($digit[0]+1); //"prints" H11
Demo

How do I get the last part of a string in PHP

I have many strings that follow the same convention:
this.is.a.sample
this.is.another.sample.of.it
this.too
What i want to do is isolate the last part. So i want "sample", or "it", or "too".
What is the most efficient way for this to happen. Obviously there are many ways to do this, but which way is best that uses the least resources (CPU and RAM).
$string = "this.is.another.sample.of.it";
$contents = explode('.', $string);
echo end($contents); // displays 'it'
I realise this question is from 2012, but the answers here are all inefficient. There are string functions built into PHP to do this, rather than having to traverse the string and turn it into an array, and then pick the last index, which is a lot of work to do something quite simple.
The following code gets the last occurrence of a string within a string:
strrchr($string, '.'); // Last occurrence of '.' within a string
We can use this in conjunction with substr, which essentially chops a string up based on a position.
$string = 'this.is.a.sample';
$last_section = substr($string, (strrchr($string, '-') + 1));
echo $last_section; // 'sample'
Note the +1 on the strrchr result; this is because strrchr returns the index of the string within the string (starting at position 0), so the true 'position' is always 1 character on.
http://us3.php.net/strpos
$haystack = "this.is.another.sample.of.it";
$needle = "sample";
$string = substr( $haystack, strpos( $haystack, $needle ), strlen( $needle ) );
Just do:
$string = "this.is.another.sample.of.it";
$parts = explode('.', $string);
$last = array_pop(parts);
$new_string = explode(".", "this.is.sparta");
$last_part = $new_string[count($new_string)-1];
echo $last_part; // prints "sparta".
$string = "this.is.another.sample.of.it";
$result = explode('.', $string); // using explode function
print_r($result); // whole Array
Will give you
result[0]=>this;
result[1]=>is;
result[2]=>another;
result[3]=>sample;
result[4]=>of;
result[5]=>it;
Display any one you want (ex. echo result[5];)

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

Categories