Get 2 words within a string using PHP - php

I am trying to get 2 words from a string, where the 2 words can be different each time.
In this example, I'm trying to get Open and On Hold
$str = 'Status Changed from Open to On Hold';
I've managed to get Open with this code:
$starting_word = 'Status Changed from';
$ending_word = 'to';
$subtring_start = strpos($str, $starting_word).strlen($starting_word);
$size = strpos($str, $ending_word, $subtring_start) - $subtring_start;
$a = substr($str, $subtring_start, $size);
And then I tried to get On Hold using this, but it's returning nothing.
$subtring_start = strpos($str, $a);
$size = strpos($str, '', $subtring_start) - $subtring_start;
$b = substr($str, $subtring_start, $size);
echo $b;

You'll get some good answers on how to do it similar to your approach, but this is easier:
preg_match('/ from ([^ ]+) to (.*)/', $str, $matches);
echo $matches[1];
echo $matches[2];
match a space and from and a space
capture () anything not a space [^ ]+ up to a space and to
capture () anything .* to the end

Even though you haven't made clear what the specific dynamic words are, but you can try the following code to get the second string, that is, in your case, 'On Hold'.
$str = 'Status Changed from Open to On Hold';
$starting_word = 'Status Changed from';
$ending_word = 'to';
$size = strpos($str, $ending_word);
$second_value = substr($str, $size+3);
echo $second_value;
Output:
On Hold
Try and change the 'On Hold' in your $str and run the code again, and see the magic.
Try it online!

Related

How to replace a letter in a sea of recurring letter with php?

$aEnd = "123/123/432/Omeagle";
$aEnd = str_replace("/", "-", $aEnd); // Output: "123-123-432-Omeagle"
$finda = strpos($aEnd, "-");
$countHypen = 0;
$wordLength = 0;
foreach($aEnd as $word){
$wordLength += 1;
if($word == "-"){
$countHypen +=1;
if($countHypen == $finda){
break;
}
}
$aEnd = substr_replace($aEnd," ",$wordLength, 1);
}
Problem
As you can see from the code above, I am trying to replace the fourth occurrence of the word but the way I did it is super duper inefficient as I have to run this portion quite a lot of times plus the length of the $aEnd is always changing.
Question
Is there any better way? Thanks.
Expecting Output
From: 123/123/432/Omeagle
To: 123-123-432 Omeagle
preg_replace should work here, using the following pattern:
\/(?=.*\/)
This will target any path separator which is not the final one, and then we replace it with dash. After this, we make a single call to str_replace to replace the final remaining path separator with a space.
$aEnd = "123/123/432/Omeagle";
$output = preg_replace("/\/(?=.*\/)/", "-", $aEnd);
$output = str_replace("/", " ", $output);
echo $output;
This prints:
123-123-432 Omeagle
You can do all the replacements in one call to preg_replace, replacing / that are followed by another / (/(?=.*/)) with -, and a / not followed by / (/(?=[^/]*$)) with a space:
$aEnd = "123/123/432/Omeagle";
$aEnd = preg_replace(array('#/(?=.*/)#', '#/(?=[^/]*$)#'), array('-', ' '), $aEnd);
echo $aEnd;
Output:
123-123-432 Omeagle
Demo on 3v4l.org

how to get string between .ism and slash before it using php?

I have a large string and want to extract data between .ism and the slash / before it. For example I want to get: life-episode-galaxy
My current code gives all data before .ism. Could anyone tell me what is wrong here and how to get only data between .ism and slash / before it?
<?
$code="media=http://somesite.com/4534543kjlkljklkjlkkljlkdsfsfo/life-episode-galaxy.ism/manifest,deliverymethod=adaptiv";
$startsAt3 = strpos($code, "/") + strlen("/");
$endsAt3 = strpos($code, ".ism", $startsAt3);
$result3 = substr($code, $startsAt3, $endsAt3 - $startsAt3);
echo $result3;
?>
I Assume your link would have always the same number of slashes / you can just explode into an array and output the right element, removing the not needed data with str_replace
$code="media=http://somesite.com/4534543kjlkljklkjlkkljlkdsfsfo/life-episode-galaxy.ism/manifest,deliverymethod=adaptiv";
$array = explode("/", str_replace("//", "/", $code));
echo str_replace('.ism', '', $array[3]);
This will output
life-episode-galaxy
Live Sample
You could use a regexp, but that's boring.
You can use strrpos with the 3rd offset parameter, using a negative offset.
$ism_pos = strpos($code, ".ism");
$last_slash_pos_before_ism = strrpos($code, "/", $ism_pos - strlen($code));
$result = substr($code, $last_slash_pos_before_ism, $ism_pos);
Might be off-by-one here and there, check it.
I would use regex:
$pattern = '#/(.*)\.ism/#U';
$matches = array();
$found = preg_match($pattern, $string, $matches);
if (1 === $found) {
$your_desired_string = $matches[1];
} else {
// not found
}

Get the current + the next word in a string

this is what I try to get:
My longest text to test When I search for e.g. My I should get My longest
I tried it with this function to get first the complete length of the input and then I search for the ' ' to cut it.
$length = strripos($text, $input) + strlen($input)+2;
$stringpos = strripos($text, ' ', $length);
$newstring = substr($text, 0, strpos($text, ' ', $length));
But this only works first time and then it cuts after the current input, means
My lon is My longest and not My longest text.
How I must change this to get the right result, always getting the next word. Maybe I need a break, but I cannot find the right solution.
UPDATE
Here is my workaround till I find a better solution. As I said working with array functions does not work, since part words should work. So I extended my previous idea a bit. Basic idea is to differ between first time and the next. I improved the code a bit.
function get_title($input, $text) {
$length = strripos($text, $input) + strlen($input);
$stringpos = stripos($text, ' ', $length);
// Find next ' '
$stringpos2 = stripos($text, ' ', $stringpos+1);
if (!$stringpos) {
$newstring = $text;
} else if ($stringpos2) {
$newstring = substr($text, 0, $stringpos2);
} }
Not pretty, but hey it seems to work ^^. Anyway maybe someone of you have a better solution.
You can try using explode
$string = explode(" ", "My longest text to test");
$key = array_search("My", $string);
echo $string[$key] , " " , $string[$key + 1] ;
You can take i to the next level using case insensitive with preg_match_all
$string = "My longest text to test in my school that is very close to mY village" ;
var_dump(__search("My",$string));
Output
array
0 => string 'My longest' (length=10)
1 => string 'my school' (length=9)
2 => string 'mY village' (length=10)
Function used
function __search($search,$string)
{
$result = array();
preg_match_all('/' . preg_quote($search) . '\s+\w+/i', $string, $result);
return $result[0];
}
There are simpler ways to do that. String functions are useful if you don't want to look for something specific, but cut out a pre-defined length of something. Else use a regular expression:
preg_match('/My\s+\w+/', $string, $result);
print $result[0];
Here the My looks for the literal first word. And \s+ for some spaces. While \w+ matches word characters.
This adds some new syntax to learn. But less brittle than workarounds and lengthier string function code to accomplish the same.
An easy method would be to split it on whitespace and grab the current array index plus the next one:
// Word to search for:
$findme = "text";
// Using preg_split() to split on any amount of whitespace
// lowercasing the words, to make the search case-insensitive
$words = preg_split('/\s+/', "My longest text to test");
// Find the word in the array with array_search()
// calling strtolower() with array_map() to search case-insensitively
$idx = array_search(strtolower($findme), array_map('strtolower', $words));
if ($idx !== FALSE) {
// If found, print the word and the following word from the array
// as long as the following one exists.
echo $words[$idx];
if (isset($words[$idx + 1])) {
echo " " . $words[$idx + 1];
}
}
// Prints:
// "text to"

How to get everything after a certain character?

I've got a string and I'd like to get everything after a certain value. The string always starts off with a set of numbers and then an underscore. I'd like to get the rest of the string after the underscore. So for example if I have the following strings and what I'd like returned:
"123_String" -> "String"
"233718_This_is_a_string" -> "This_is_a_string"
"83_Another Example" -> "Another Example"
How can I go about doing something like this?
The strpos() finds the offset of the underscore, then substr grabs everything from that index plus 1, onwards.
$data = "123_String";
$whatIWant = substr($data, strpos($data, "_") + 1);
echo $whatIWant;
If you also want to check if the underscore character (_) exists in your string before trying to get it, you can use the following:
if (($pos = strpos($data, "_")) !== FALSE) {
$whatIWant = substr($data, $pos+1);
}
strtok is an overlooked function for this sort of thing. It is meant to be quite fast.
$s = '233718_This_is_a_string';
$firstPart = strtok( $s, '_' );
$allTheRest = strtok( '' );
Empty string like this will force the rest of the string to be returned.
NB if there was nothing at all after the '_' you would get a FALSE value for $allTheRest which, as stated in the documentation, must be tested with ===, to distinguish from other falsy values.
Here is the method by using explode:
$text = explode('_', '233718_This_is_a_string', 2)[1]; // Returns This_is_a_string
or:
$text = end((explode('_', '233718_This_is_a_string', 2)));
By specifying 2 for the limit parameter in explode(), it returns array with 2 maximum elements separated by the string delimiter. Returning 2nd element ([1]), will give the rest of string.
Here is another one-liner by using strpos (as suggested by #flu):
$needle = '233718_This_is_a_string';
$text = substr($needle, (strpos($needle, '_') ?: -1) + 1); // Returns This_is_a_string
I use strrchr(). For instance to find the extension of a file I use this function:
$string = 'filename.jpg';
$extension = strrchr( $string, '.'); //returns "jpg"
Another simple way, using strchr() or strstr():
$str = '233718_This_is_a_string';
echo ltrim(strstr($str, '_'), '_'); // This_is_a_string
In your case maybe ltrim() alone will suffice:
echo ltrim($str, '0..9_'); // This_is_a_string
But only if the right part of the string (after _) does not start with numbers, otherwise it will also be trimmed.
if anyone needs to extract the first part of the string then can try,
Query:
$s = "This_is_a_string_233718";
$text = $s."_".substr($s, 0, strrpos($s, "_"));
Output:
This_is_a_string
$string = "233718_This_is_a_string";
$withCharacter = strstr($string, '_'); // "_This_is_a_string"
echo substr($withCharacter, 1); // "This_is_a_string"
In a single statement it would be.
echo substr(strstr("233718_This_is_a_string", '_'), 1); // "This_is_a_string"
If you want to get everything after certain characters and if those characters are located at the beginning of the string, you can use an easier solution like this:
$value = substr( '123_String', strlen( '123_' ) );
echo $value; // String
Use this line to return the string after the symbol or return the original string if the character does not occur:
$newString = substr($string, (strrpos($string, '_') ?: -1) +1);

string between, php

as I am new to php, and after googling :) I still could not find what I wanted to do.
I have been able to find start and end position in string that i want to extract but most of the example use strings or characters or integers to get string between but I could not find string bewteen two positions.
For example:
$string = "This is a test trying to extract";
$pos1 = 9; $pos2 = 14;
Then I get lost. I need to get the text between position 9 and 14 of of the string.
Thanks.
$startIndex = min($pos1, $pos2);
$length = abs($pos1 - $pos2);
$between = substr($string, $startIndex, $length);
You can use substr() to extract part of a string. This works by setting the starting point and the length of what you want to extract.
So in your case this would be:
$string = substr($string,9,5); /* 5 comes from 14-9 */
<?php
$string = "This is a test trying to extract";
$pos1 = 9;
$pos2 = 14;
$start = min($pos1, $pos2);
$length = abs($pos1 - $pos2);
echo substr($string, $start - 1, $length); // output 'a test'
?>

Categories