How to extract substring from duplicate strings? - php

i have a specific problem .I am retrieving data in string format in PHP. I have to seperate the specific values from the string.My string looks like this
Barcode formatQR_CODEParsed Result TypeURIParsed Resulthttp://www.myurl.co.uk var ga.
Barcode formatQR_CODEParsed Result TypeTEXTParsed ResultMy Coat var ga.
As you can see from above two examples, The text after "Barcode formatQR_CODEParsed Result Type" and "Parsed Result" are changing.
I have tried strstr function but it is not giving me desired output as the words "Parsed Result" is repeating twice.How can i extract ANY value /text that will come after these?How can I separate them?I would appreciate if someone could guide as i am new bee.
Thanks

The fastest way is to parse this piece of HTML code with SimpleXML and get <b> children's values.

just walk through the strings until you find the first difference. Shouldn't be a problem?
$str1 = "Hello World";
$str2 = "Hello Earth";
for($i=0; $<min(strlen($str1),strlen($str2)); $i++){
if ($str1[$i] != $str2[$i]){
echo "Difference starting at pos $i";
}
}
or something like that. Then you can use substr to remove the equal part.
edit: IF your Strings always have the same Pattern, with values enclosed in <b> you can perfectly use a Regular-Expression to get the values.

I have found the solution .We can extract strings this way:
<?
$mycode='Barcode formatQR_CODEParsed Result TypeURIParsed Resulthttp://www.myurl.co.uk var ga';
$needle = 'Parsed Result';
$chunk=explode($needle,$mycode);
$mychunky= $chunk[2];
$needle = 'var ga';
$result = substr($mychunky, 0, strpos($mychunky, $needle));
print($result);
?>

This should work for you. Also you can extend this idea futher and develop by your own needs.
$string = "Barcode formatQR_CODEParsed Result TypeURIParsed Resulthttp://www.myurl.co.uk var ga." ;
$matches = array() ;
$pattern = "/Type([A-Z]+)Parsed Result([^>]+) var ga./" ;
preg_match($pattern, $string, $matches) ; // Returns boolean, but we need matches.
Then get the occurences:
$matches[0] ; // The whole occurence
$matches[1] ; // Type - "([A-Z]+)"
$matches[2] ; // Result - "([^>]+)"
So you use elements with indeces 1 and 2 as Type and Result respectively. Hope it can help.

Related

How to Get specifit character in string in php

i want to get a word until a spesicif character, example space. i trying to use substr but i cant.
Assumming i have column data :
1. 3/14/2016 13:46
i would like to get 3/14/2016 and showing it. is that possible?
2. 3/14/2016 13:46
i would like to get 13.46 without date. is that possible?
can someone tell me how to get string from 2 case above.
thanks a lot
If the columns are space delimited then you can use an explode and pull the index of the column of which you want.
$rowData = "1. 3/14/2016 13:46";
$rowCols = explode(" ",$rowData);
echo $rowCols[1]; // returns 3/14/2016
echo $rowCols[2]; // returns 13:46
$specifidCharacter = " " //Space for example
$string = "1. 3/14/2016 13:46";
$tmp = explode($specificCharacter, $string);
echo $tmp[1] //Case 1
echo $tmp[2] //Case 2

remove a sentence in php string that contains certain words

I have the following string
"This is very nice. Thanks for your support."
Now I want to remove the line that contains Thanks word
you need to explode the paragraph by fullstop.
lets say your full paragraph is store in $str
$lines_arr = explode(".",$str);
now $lines_arr is an array contains numbers of lines.
now under loop you can check which lines contains "thanks" , if it is then skip it.
$string = '';
for($i=0; $i<(count($lines_arr)-1); $i++){
//with the help of strpos
if(strpos($lines_arr[$i],"Thanks") == false){
$string .= $lines_arr[$i].". ";
}
}
you can use str_replace
echo str_replace("Thanks", "", "This is very nice. Thanks for your support.");
# Output: This is very nice. for your support.
If you expect proper punctuation, you could explode() the string into an array on the full stops and delete the elements with your particular word, then merge all the elements back into a string.

How to search for a pattern like [num:0] and replace it?

I know there are lots of tutorials and question on replacing something in a string.
But I can't find a single one on what I want to do!
Lets say I have a string like this
$string="Hi! [num:0]";
And an example array like this
$array=array();
$array[0]=array('name'=>"na");
$array[1]=array('name'=>"nam");
Now what I want is that PHP should first search for the pattern like [num:x] where x is a valid key from the array.
And then replace it with the matching key of the array. For example, the string given above should become: Hi! na
I was thinking of doing this way:
Search for the pattern.
If found, call a function which checks if the number is valid or not.
If valid, returns the name from the array of that key like 0 or 1 etc.
PHP replaces the value returned from the function in the string in place of the pattern.
But I can't find a way to execute the idea. How do I match that pattern and call the function for every match?
This is just the way that I am thinking to do. Any other method will also work.
If you have any doubts about my question, please ask in comments.
Try this
$string="Hi! [num:0]";
$array=array();
$array[0]=array('name'=>"na");
$array[1]=array('name'=>"nam");
echo preg_replace('#(\!)?\s+\[num:(\d+)\]#ie','isset($array[\2]) ? "\1 ".$array[\2]["name"] : " "',$string);
If you don't want the overhead of Regex, and your string format remains same; you could use:
<?php
$string="Hi! [num:0]";
echo_name($string); // Hi John
echo "<br />";
$string="Hello! [num:10]";
echo_name($string); // No names, only Hello
// Will echo Hi + Name
function echo_name($string){
$array=array();
$array[0]=array('name'=>"John");
$array[1]=array('name'=>"Doe");
$string = explode(" ", $string);
$string[1] = str_replace("[num:", "", $string[1]);
$string[1] = str_replace("]", "", $string[1]);
if(array_key_exists($string[1], $array)){
echo $string[0]." ".$array[$string[1]]["name"];
} else {
echo $string[0]." ";
}
}// function echo_sal ENDs
?>
Live: http://codepad.viper-7.com/qy2uwW
Assumptions:
$string always will have only one space, exactly before [num:X].
[num:X] is always in the same format.
Of course you could skip the str_replace lines if you could make your input to simple
Hi! 0 or Hello! 10

How to get a matching string by comparing 2 strings?

I was once asked a question in an interview that if we have 2 strings, how we can get a part of matching string from these two?
for example
$str1 = "My name is baig";
$str2 = "Baig is a nice person";
now i want the output
"i a e s g" and other matching letters
I want this in Php
Thanks in advance
this is code to get the expected result for two string str1 and str2
<?php
$str1 = strtolower("My name is baig");
$str2 = strtolower("Baig is a nice person");
$array1 = explode(' ',$str1);
$array2 = explode(' ',$str2);
$result = array_intersect($array2, $array1);
print_r(implode(' ',$result));
?>
Well you have several options...
If you want matches in a specific order, meaning is a string inside another string, you might go for strstr, if you want to find any common point between 2 strings, you might want to first find an explode pattern, in your case a space.
Expode both string and intersect both arrays.
You can use array_intersect after use the function explode on your string.
A working example :
http://codepad.org/IikNr2Vv
But this is case sensitive, Baig will be different of baig.
To resolve this, you can use the strtolower function to transform to lower cas all your string.
got the following answer from another forum
<?php
$str1 = "My name is baig";
$str2 = "Baig is a nice person";
$r1 = str_split(preg_replace("/[^a-zA-z]/","",strtolower($str1)));
$r2 = str_split(preg_replace("/[^a-zA-z]/","",strtolower($str2)));
$match = array_unique(array_intersect($r1,$r2));
$match = implode(" ",$match);
echo "Matched letters are: ".$match;
?>
Case sensitivity is still an issue but i will go through it

PHP : Get a number between 2 strings

I have this string:
a:3:{i:0;i:2;i:1;i:3;i:2;i:4;}
I want to get number between "a:" and ":{" that is "3".
I try to user substr and strpos but no success.
I'm newbie in regex , write this :
preg_match('/a:(.+?):{/', $v);
But its return me 1.
Thanks for any tips.
preg_match returns the number of matches, in your case 1 match.
To get the matches themselves, use the third parameter:
$matches = array();
preg_match(/'a:(\d+?):{/', $v, $matches);
That said, I think the string looks like a serialized array which you could deserialize with unserialize and then use count on the actual array (i.e. $a = count(unserialize($v));). Be careful with userprovided serialized strings though …
If you know that a: is always at the beginning of the string, the easiest way is:
$array = explode( ':', $string, 3 );
$number = $array[1];
You can use sscanfDocs to obtain the number from the string:
# Input:
$str = 'a:3:{i:0;i:2;i:1;i:3;i:2;i:4;}';
# Code:
sscanf($str, 'a:%d:', $number);
# Output:
echo $number; # 3
This is often more simple than using preg_match when you'd like to obtain a specific value from a string that follows a pattern.
preg_match() returns the number of times it finds a match, that's why. you need to add a third param. $matches in which it will store the matches.
You were not too far away with strpos() and substr()
$pos_start = strpos($str,'a:')+2;
$pos_end = strpos($str,':{')-2;
$result = substr($str,$pos_start,$pos_end);
preg_match only checks for appearance, it doesn't return any string.

Categories