Extract a particular string form a long string in php - php

I have this string "PAX 098-5503268037/ETAI/USD107.75/15MAY20/KTMVS31KL/10303171" and would like to extract the USD107.75.I have this function:
Here:
$str = PAX 098-5503268037/ETAI/USD107.75/15MAY20/KTMVS31KL/10303171;
$from = '/ETAI';
$to = '/';
public function getStringBetween($str,$from,$to)
{
$sub = substr($str, strpos($str,$from)+strlen($from),strlen($str));
return substr($sub,0,strpos($sub,$to));
}
The function only return an empty string.
What am I missing?
Thanks

If you do a bit of debugging...
public function getStringBetween($str,$from,$to)
{
$sub = substr($str, strpos($str,$from)+strlen($from),strlen($str));
echo $sub.PHP_EOL;
return substr($sub,0,strpos($sub,$to));
}
you will see the interim output is
/USD107.75/15MAY20/KTMVS31KL/10303171
as you then look for the first / and extract up to that, that is the first character.
A simple solution to what you already have is to add +1 in the start position...
public function getStringBetween($str,$from,$to)
{
$sub = substr($str, strpos($str,$from)+strlen($from)+1,strlen($str));
return substr($sub,0,strpos($sub,$to));
}
Alternatively, you can as u_mulder indicated, explode() on / and then extract the part you are after...
echo explode("/", $str)[2];

Related

remove front and last of the character of a string in php

My goal is to create a function that removes the first and last characters of a string in php.
My code:
function remove_char(string $s): string {
$len = strlen($s);
return substr($s,1,$len-2);
}
This not past the codewar code test. Can anyone tell me why it is not correct?
The built in function substr is accepting negative value, when you use negative value it affect readability. You can also give the function name better and clearer name like so:
function modify_string(string $s): string {
return substr($s, 1, -1);
}
try this code.
function remove_char(string $s){
if(strlen($s) > 1){
return substr($s, 1, -1);
}
return false;
}
<?php
function remove($word){
$result = substr($word, 1, -1);
return $result;
}
$word = 'HELLO';
$results = remove($word);
echo $results;
?>
Demo

Search elements inside string

Let me explain what I want to do.
I need to connect to a device using SSH and execute some shell commands. I get the result of these commands (stream, using ssh2_fetch_stream) and save into a variable. This Works fine.
But what I need to know is how can I search by elements in a string?
Here a sample string:
$stringToSearch = "id=10 name=interfacename1 stringx=102040 stringy=50606040,id=20 name=interfacename2 stringx=872345 stringy=23875454,id=30 name=interfacename3 stringx=654389 stringy=34567865";
I need to obtain all the 'name=' results, like (SELECT name FROM stringToSearch;) and this would return:
____name____
interfacename1
interfacename2
interfacename3
I created a simple function to read this string.
<?php
function readString($stringToSearch, $start, $end) {
$result = '-1';
// I need to do a loop here, but how can I do it to read and return all elements between $start and $end?
if(strlen(strstr($stringToSearch, $start)) > 0)
{
$startsAt = strpos($stringToSearch, $start) + strlen($start);
$endsAt = strpos($stringToSearch, $end, $startsAt);
$result = substr($stringToSearch, $startsAt, $endsAt - $startsAt);
}
return $result;
}
$stringToSearch = 'id=10 name=interfacename1 stringx=102040 stringy=50606040,id=20 name=interfacename2 stringx=872345 stringy=23875454,id=30 name=interfacename3 stringx=654389 stringy=34567865';
$element = readString($stringToSearch, 'name=', ' '); // Will return only the 1st element
?>
But I can only retrieve the 1st element. How can I get all the elements in this string?
try with this solution :)
<?php
$stringToSearch = "id=10 name=interfacename1 stringx=102040 stringy=50606040,id=20 name=interfacename2 stringx=872345 stringy=23875454,id=30 name=interfacename3 stringx=654389 stringy=34567865";
var_dump(getName($stringToSearch));
function getName($stringToSearch) {
$pattern = '/name=([A-Z0-9]*)/i';
if(preg_match_all($pattern, $stringToSearch, $result) == 0){
return NULL;
}
return $result[1];
}
Enhancement (to get all values of desired parameter):
/**
* #param String $varName : the name of variable to get their values. ex: stringx, stringy
* #param String $stringToSearch : the string to search in
* #return Array if variable was found in $stringToSearch, NULL else
*/
function getName($varName, $stringToSearch) {
$pattern = '/' . $varName . '=([A-Z0-9]*)/i';
if(preg_match_all($pattern, $stringToSearch, $result) == 0){
return NULL;
}
return $result[1];
}
Using Halayem Anis's answer I was able to find all the elements in the string.
But I found other problem. If I have a string like that: name="foo bar" (with space at the middle).
To solve this problem I adapted the $pattern.
The result is:
//$varname = string to be searched like name=
//$stringToSearch = the original string
function getName($varName, $stringToSearch) {
$pattern = '/(?<=' . $varName . ')"(.*?)"/i'; // Changed this to get all between name=""
if(preg_match_all($pattern, $stringToSearch, $result) == 0){
return NULL;
}
return $result[1];
}

PHP Strings/Functions: Converting a string into a chain of functions

Having a string like
12345.find_user.find_last_name
how can i split at the charachter "." and convert it to a function-call:
find_last_name(find_user(12345));
and so on....could be of N-Elements (n-functions to run)....how do i do this effectivly, performance-wise also?
Edit, here is the solution based on your replies
thanks Gaurav for your great help. Here is my complete solution based on yours:
i protected the foreach with if(function_exists($function)){ to protect the whole thing from fatal php errors, and i added a complete example:
$mystring = '12345.find_user.find_last_name';
convert_string_to_functions($mystring);
function convert_string_to_functions($mystring){
$functions = explode('.', $mystring);
$arg = array_shift($functions);
foreach($functions as $function){
if(function_exists($function)){
$arg = $function($arg);
} else {
echo 'Function '.$function.' Not found';
}
}
echo $arg;
}
function find_last_name($mystring=''){
return $mystring.' i am function find_last_name';
}
function find_user($mystring=''){
return $mystring.' i am function find_user';
}
$string = '12345.find_user.find_last_name';
$functions = explode('.', $string);
$arg = array_shift($functions);
foreach($functions as $function){
$arg = $function($arg);
}
echo $arg;

Get Part of the String if with conditional prefix [+ and suffix +]

How can I get part of the string with conditional prefix [+ and suffix +], and then return all of it in an array?
example:
$string = 'Lorem [+text+] Color Amet, [+me+] The magic who [+do+] this template';
// function to get require
function getStack ($string, $prefix='[+', $suffix='+]') {
// how to get get result like this?
$result = array('text', 'me', 'do'); // get all the string inside [+ +]
return $result;
}
many thanks...
You can use preg_match_all as:
function getStack ($string, $prefix='[+', $suffix='+]') {
$prefix = preg_quote($prefix);
$suffix = preg_quote($suffix);
if(preg_match_all("!$prefix(.*?)$suffix!",$string,$matches)) {
return $matches[1];
}
return array();
}
Code In Action
Here’s a solution with strtok:
function getStack ($string, $prefix='[+', $suffix='+]') {
$matches = array();
strtok($string, $prefix);
while (($token = strtok($suffix)) !== false) {
$matches[] = $token;
strtok($prefix);
}
return $matches;
}

built in function to combine overlapping string sequences in php?

Is there a built in function in PHP that would combine 2 strings into 1?
Example:
$string1 = 'abcde';
$string2 = 'cdefg';
Combine to get: abcdefg.
If the exact overlapping sequence and the position are known, then it is possible to write a code to merge them.
TIA
I found the substr_replace method to return funny results.
Especially when working with url strings. I just wrote this function.
It seems to be working perfectly for my needs.
The function will return the longest possible match by default.
function findOverlap($str1, $str2){
$return = array();
$sl1 = strlen($str1);
$sl2 = strlen($str2);
$max = $sl1>$sl2?$sl2:$sl1;
$i=1;
while($i<=$max){
$s1 = substr($str1, -$i);
$s2 = substr($str2, 0, $i);
if($s1 == $s2){
$return[] = $s1;
}
$i++;
}
if(!empty($return)){
return $return;
}
return false;
}
function replaceOverlap($str1, $str2, $length = "long"){
if($overlap = findOverlap($str1, $str2)){
switch($length){
case "short":
$overlap = $overlap[0];
break;
case "long":
default:
$overlap = $overlap[count($overlap)-1];
break;
}
$str1 = substr($str1, 0, -strlen($overlap));
$str2 = substr($str2, strlen($overlap));
return $str1.$overlap.$str2;
}
return false;
}
Usage to get the maximum length match:
echo replaceOverlap("abxcdex", "xcdexfg"); //Result: abxcdexfg
To get the first match instead of the last match call the function like this:
echo replaceOverlap("abxcdex", "xcdexfg", “short”); //Result: abxcdexcdexfg
To get the overlapping string just call:
echo findOverlap("abxcdex", "xcdexfg"); //Result: array( 0 => "x", 1 => "xcdex" )
It's possible using substr_replace() and strcspn():
$string1 = 'abcde';
$string2 = 'cdefgh';
echo substr_replace($string1, $string2, strcspn($string1, $string2)); // abcdefgh
No, there is no builtin function, but you can easily write one yourself by using substr and a loop to see how much of the strings that overlap.

Categories