Check If a String Is Present and Its Position - php

Sorry, a bit new to php. Have tried all I know, but failed and seeking expert help.
I have a string similar to this..
/%mydocs%/%myfolder%/%date%/%filename%.html
Basically the %vars% represents different strings and seperated by /, like a URL.
I need to find %date% (or any given variable) if it's present and it's position in the string, like it's at position 3 in the example above.
I tried this,
$date = preg_match( '%date%', '/%mydocs%/%myfolder%/%date%/%filename%.html');
But it's neither returning anything nor the position.
Any help, even some heads up to play with, will be appriciated.

strpos
<?php
$mystring = '/%mydocs%/%myfolder%/%date%/%filename%.html';
$findme = '%date%';
$pos = strpos($mystring, $findme);
if ($pos === false) {
echo "The string '$findme' was not found in the string '$mystring'";
} else {
echo "The string '$findme' was found in the string '$mystring'";
echo " and exists at position $pos";
}
?>
Result:
The string '%date%' was found in the string '/%mydocs%/%myfolder%/%date%/%filename%.html' and exists at position 21

How about using preg_split:
$var = '%date%';
$str = '/%mydocs%/%myfolder%/%date%/%filename%.html';
$list = preg_split('#/#', $str, -1, PREG_SPLIT_NO_EMPTY);
for($i=0; $i<count($list); $i++) {
if ($list[$i] == $var) {
echo "Found $var at position ",$i+1,"\n";
}
}
output:
Found %date% at position 3

preg_match returns a boolean for whether there was a match or not, but you can pass a third parameter - $matches, which will contain the matches according to the regular expression provided.
You don't look to be using a regular expressions - for what you are doing you probably want to look at strpos instead. http://uk3.php.net/strpos

Related

Match multiple strings

I'm trying to see whether or not 2 strings match.
example: 1234.5678.9012.3456 => 5678.1234.3456 = match
This matches because the second string of number are also in the first one. I did this with the following code:
<?php
$haystack = '1234.5678.9012.3456';
$needle = '5678.1234.3456';
$regex = '/(?=.*'. str_replace(".",")(?=.*",$needle) .').*$/';
// regex looks like this /(?=.*5678)(?=.*1234)(?=.*3456).*$/
if(preg_match($regex, $haystack)){
echo "A match was found.";
} else {
echo "A match was not found.";
}
?>
Here is my problem, when there are duplicate numbers.
example: 1234.5678.9012.3456 => 5678.5678.3456 = dont match
1234.5678.5678.3456 => 5678.5678.3456 = match
The first example doesnt match because 5678 occurs twice but the first string only has 5678 once. In the second example 5678 occurs twice as well and therefor matches the second string.
My question: How could I change my regex,
You choose a very complicated way to do that. You can check what you want in a more simple way using array_diff:
var_dump(array_diff(explode('.', $needle), explode('.', $haystack)));
when the resulting array is empty the condition is true.
Try this:
<?php
$haystack = '1234.5678.9012.3456';
$needle = '5678.5678.3456';
$needle_array = explode(".", $needle);
//print_r($needle_array);
$haystack_array = explode(".", $haystack);
//print_r($haystack_array);
$intersect = array_intersect($needle_array, $haystack_array);
//print_r($intersect);
if(count($intersect) > 0){
echo "Match";
} else {
echo "Doesn't match";
}
?>

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
}
}

Skip the sentence that has certain first word

I want to check the first word of some sentences. If the first word are For, And, Nor, But, Or, etc, I want to skip the sentence.
Here's the code :
<?php
$sentence = 'For me more';
$arr = explode(' ',trim($sentence));
if(stripos($arr[0],'for') or stripos($arr[0],'but') or stripos($arr[0],'it')){
//doing something
}
?>
Blank result, Whats wrong ? thank you :)
Here, stripos will return 0 if the word is found (found at position 0).
It returns false if the word is not found.
You should write :
if(stripos($arr[0],'for') !== false or stripos($arr[0],'but') !== false or stripos($arr[0],'it') !== false){
//skip
}
Stripos returns the position on the first occurrence of the needle in the haystack
The first occurrence is at position 0, which evaluates to false.
Try this as an alternative
$sentence = 'For me more';
// make all words lowercase
$arr = explode(' ', strtolower(trim($sentence)));
if(in_array($arr[0], array('for', 'but', 'it'))) {
//doing something
echo "found: $sentence";
} else {
echo 'failed';
}
Perhaps use preg_filter if you are going to know what the string to be evaluated is (i.e. you don't need to parse out sentences).
$filter_array = array(
'/^for\s/i',
'/^and\s/i',
'/^nor\s/i',
// etc.
}
$sentence = 'For me more';
$result = preg_filter(trim($sentence), '', $filter_array);
if ($result === null) {
// this sentence did not match the filters
}
This allows you to determine a set of filter regex patterns to see if you have a match. Note that in this case I just used '' as "replacement" value, as you don't really care about actually making a replacement, this function just gives you a nice way to pas in an array of regular expressions.

Find exact string in string - PHP

How do I find exact 2, in a string using strpos? Is it possible using strpos? The example below returns "Found" even though the match is NOT exact to what I need. I understand 2, is matching with 22,. It should return "Not Found". I am matching ID's in this example.
$string = "21,22,23,26,";
$find = "2,";
$pos = strpos($string, $find);
if ($pos !== false) {
echo "Found";
} else {
echo "Not Found";
}
Unless the string is enormous, make an array and search it:
$string = "21,22,23,26,";
$arr = explode(",", $string);
// array_search() returns its position in the array
echo array_search("2", $arr);
// null output, 2 wasn't found
Actually, in_array() is probably faster:
// in_array() returns a boolean indicating whether it is found or not
var_dump(in_array("2", $arr));
// bool(false), 2 wasn't found
var_dump(in_array("22", $arr));
// bool(true), 22 was found
This will work as long as your string is a comma-delimited list of values. If the string is really long, making an array may be wasteful of memory. Use a string manipulation solution instead.
Addendum
You didn't specify, but if by some chance these strings came from a database table, I would just add that the appropriate course of action would be to properly normalize it into another table with one row per id rather than store them as a delimited string.
Try with explode and in_array
Example:
$string = "21,22,23,26,";
$string_numbers = explode(",", $string);
$find = 2;
if (in_array($find, $string_numbers)) {
echo "Found";
} else {
echo "Not Found";
}
You can use preg_match if you want to avoid arrays.
$string = "21,22,23,26,";
$find = '2';
$pattern = "/(^$find,|,$find,|,$find$)/";
if (0 === preg_match($pattern, $string)) {
echo "Not Found";
} else {
echo "Found";
}
This will find your id at beginning, middle or at the end of the string. Of course, I am assuming $string does not contain characters other than numbers and commas (like spaces).

need help with using stristr

I need help return everything after "I can read." I understand that this will search the string and find whats in the array $check but how do I make it check and then return all whats found after "I can read"?
$string = "I can read. I can count. I can spell.";
$check = array("I can count.", "I can't count.");
$find = stristr($string, $check, true);
echo $find;
$find = 'I can read.';
$string = '[...]';
echo substr($string,stripos($string,$find)+strlen($find));
Here is what the docs say the second parameter (needle) of stistr:
If needle is not a string, it is converted to an integer and applied as
the ordinal value of a character.
Then you have to define $check as follow:
$check = "I can read";
you do not need the third parameter if you want to get the substring after $check, documentation states:
If TRUE, stristr() returns the part of the haystack before the
first occurrence of the needle.
That's why you have to call stristr with only two arguments:
$find = stristr($string, $check);

Categories