Find words in text, php - php

How to resolve this problem:
Write a PHP program that finds the word in a text.
The suffix is separated from the text by a pipe.
For example: suffix|SOME_TEXT;
input: text|lorem ips llfaa Loremipsumtext.
output: Loremipsumtext
My code is this, but logic maybe is wrong:
$mystring = fgets(STDIN);
$find = explode('|', $mystring);
$pos = strpos($find, $mystring);
if ($pos === false) {
echo "The string '$find' was not found in the string '$mystring'.";
}
else {
echo "The string '$find' was found in the string '$mystring',";
echo " and exists at position $pos.";
}

explode() returns an array, so you need to use $find[0] for the suffix, and $find[1] for the text. So it should be:
$suffix = $find[0];
$text = $find[1];
$pos = strpos($text, $suffix);
if ($pos === false) {
echo "The string '$suffix' was not found in '$text'.";
} else {
echo "The string '$suffix' was found in '$text', ";
echo " and exists at position $pos.";
}
However, this returns the position of the suffix, not the word containing it. It also doesn't check that the suffix is at the end of the word, it will find it anywhere in the word. If you want to match words rather than just strings, a regular expression would be a better method.
$suffix = $find[0];
$regexp = '/\b[a-z]*' . $suffix . '\b/i';
$text = $find[1];
$found = preg_match($regexp, $text, $match);
if ($found) {
echo echo "The suffix '$suffix' was found in '$text', ";
echo " and exists in the word '$match[0]'.";
} else {
echo "The suffix '$suffix' was not found in '$text'.";
}

Related

how i can use inverse of haystack and needle postion with strpos php function

I want to use strpos for find exploded string in the imploded array.
i have a bad list :
for example :
exam
test
i imploded those with space and in final to be like a string exam test and i have a string like this :
my string : example string
i exploded thats and having like this array :
0=> example
1=> string
now i want use strpos in inverse state like that to check example string and return me this : exam
because exam used in example word. therefore i want checking example have exam or test or not.
we know in normal strpos using like this :
$mystring = 'example string';
$mybad = array('exam', 'test');
foreach($mybad as $mybad){
$pos = strpos($mystring, $mybad);
if ($pos === false) {
echo "not found";
} else {
echo "The string '$mybad' was found in the string '$mystring'";
echo " and exists at position $pos";
}
}
but i want doing like the above description i wrote this code but doesn't work true.
$mystring = 'example string';
$mystring = explode(" ", $mystring);
$mybad = array('exam', 'test');
$mybad = implode(" ", $mybad);
foreach($mystring as $mystring){
$pos = strpos($mybad, $mystring);
if ($pos === false) {
echo "not found";
} else {
echo "The string '$mybad' was found in the string '$mystring'";
echo " and exists at position $pos";
}
}
Please help me and tell what method should I use.
thanks all.
I'm not sure if I understood what you wanted to say, but I tried to create some useful out of it. Maybe it's at least a basis to talk about.
$mystring = 'example string';
$mystring_array = explode(" ", $mystring);
$mybad_array = array('exam', 'test');
foreach($mystring_array as $mystring_element) {
foreach($mybad_array as $mybad_element) {
$pos = strpos($mystring_element, $mybad_element);
if($pos === false) {
echo "<br>The string '$mybad_element' was not found in the string '$mystring_element'";
} else {
echo "<br>The string '$mybad_element' was found in the string '$mystring_element'";
echo " and exists at position $pos";
}
}
}
This will output:
The string 'exam' was found in the string 'example' and exists at position 0
The string 'test' was not found in the string 'example'
The string 'exam' was not found in the string 'string'
The string 'test' was not found in the string 'string'

Search a PHP string for whitespace after a particular character

This is my string :
$string = '# somebody and some other stuff';
How could I detect the whitespace after the # character?
If I find the match I would like to do something with original string.
$string2 = '# ';
If I understood correctly you want to find # and remove space?
$string = str_replace("# ", "#", $string);
EDIT
You want this PHP source
<?php
$mystring = 'abc';
$findme = 'a';
$pos = strpos($mystring, $findme);
// Note our use of ===. Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
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";
}
?>
$string = preg_replace('/# (.*)/', '# ', $string);

PHP - Check if string contains illegal chars in string

In JS you can do:
var chs = "[](){}";
var str = "hello[asd]}";
if (str.indexOf(chs) != -1) {
alert("The string can't contain the following characters: " + chs.split("").join(", "));
}
How can you do this in PHP (replacing alert with echo)?
I do not want to use a regex for the simplicity of what I think.
EDIT:
What I've tried:
<?php
$chs = /[\[\]\(\)\{\}]/;
$str = "hella[asd]}";
if (preg_match(chs, str)) {
echo ("The string can't contain the following characters: " . $chs);
}
?>
Which obviously doesn't work and idk how to do it without regex.
In php you should do this:
$string = "Sometring[inside]";
if(preg_match("/(?:\[|\]|\(|\)|\{|\})+/", $string) === FALSE)
{
echo "it does not contain.";
}
else
{
echo "it contains";
}
The regex says check to see any of the characters are inside the string. you can read more about it here:
http://en.wikipedia.org/wiki/Regular_expression
And about PHP preg_match() :
http://php.net/manual/en/function.preg-match.php
Update:
I have written an updated regex for this, which captures the letters inside:
$rule = "/(?:(?:\[([\s\da-zA-Z]+)\])|\{([\d\sa-zA-Z]+)\})|\(([\d\sa-zA-Z]+)\)+/"
$matches = array();
if(preg_match($rule, $string, $matches) === true)
{
echo "It contains: " . $matches[0];
}
It returnes something like this:
It contains: [inside]
I have changed the regex only which becomes:
$rule = "/(?:(?:(\[)(?:[\s\da-zA-Z]+)(\]))|(\{)(?:[\d\sa-zA-Z]+)(\}))|(\()(?:[\d\sa-zA-Z]+)(\))+/";
// it returns an array of occurred illegal characters
It now returns [] for this "I am [good]"
Why not you try str_replace.
<?php
$search = array('[',']','{','}','(',')');
$replace = array('');
$content = 'hella[asd]}';
echo str_replace($search, $replace, $content);
//Output => hellaasd
?>
Instead of regex we can use string replace for this case.
here is a simple solution without using regex:
$chs = array("[", "]", "(", ")", "{", "}");
$string = "hello[asd]}";
$err = array();
foreach($chs AS $key => $val)
{
if(strpos($string, $val) !== false) $err[]= $val;
}
if(count($err) > 0)
{
echo "The string can't contain the following characters: " . implode(", ", $err);
}

find a specific word in external page

How to find a specific word in a external page using php ?
(dom or pregmatch, or what else ?)
example in foo.com source code with :
span name="abcd"
I want to check if the word abcd is in foo.com in php
if(preg_match('/span\s+name\=\"abcd\"/i', $str)) echo 'exists!';
To check if a string of characters exist:
<?php
$term = 'abcd';
if ( preg_match("/$term/", $str) ) {
// yes it does
}
?>
To check if that string exists as a word in its own right (ie, is not in the middle of a larger word) use word boundary matchers:
<?php
$term = 'abcd';
if ( preg_match("/\b$term\b/", $str) ) {
// yes it does
}
?>
For a case-insensitive search, add the i flag after the last slash in the regex:
<?php
$term = 'abcd';
if ( preg_match("/\b$term\b/i", $str) ) {
// yes it does
}
?>
$v = file_get_contents("http://foo.com");
echo substr_count($v, 'abcd'); // number of occurences
//or single match
echo substr_count($v, ' abcd ');
Here are other few ways to find specific word
<?php
$str = 'span name="abcd"';
if (strstr($str, "abcd")) echo "Found: strstr\n";
if (strpos($str, "abcd")) echo "Found: strpos\n";
if (ereg("abcd", $str)) echo "Found: ereg\n";
if (substr_count($str, 'abcd')) echo "Found: substr_count\n";
?>
$name = 'foo.php';
file_get_contents($name);
$contents=$pattern = preg_quote('abcd', '/');
// finalise the regular expression, matching the whole line
$pattern = "/^.*$pattern.*\$/m";
// search, and store all matching occurences in $matches
if(preg_match_all($pattern, $contents, $matches)){
echo implode("\n", $matches[0]);
}
else{
echo "not exist word";
}

php problem searching words in a text file

I use the following code to search the text file:
$query="red";
$FileName = "search.txt";
$fh = fopen($FileName, 'r') or die("Can't open file");
$data = fread($fh, filesize($FileName));
$Pos = strpos($data,$query);
if ($Pos)
{
echo "Found";
}
else
{
echo "Not Found";
}
Let the text file be:
orange_red blue_gray yellow_blue white_black
It finds red at orange_red,but i want to match the whole word.
For example:
If the text to be searched is to be red
I want it to return false because red does not exist independently it is part of word orange_red.
In brief i want to search words delimited by space
Searching red and orange should return false and searching orange_red should return true.
Split the string into an array using explode. Then search the array using array_search to see if it contains your exact word.
This is the easiest/fastest way I can think of:
$query = "red";
$FileName = "search.txt";
if(preg_match("/\b" . $query . "\b/i"), file_get_contents($FileName))
{
echo "Found";
}
else
{
echo "Not Found";
}
\b matches a word boundary, so it will only return stand-alone results for $query. preg_match returns an int denoting the number of times the pattern was found (which will be either 0 or 1, as preg_match stops after the first match - use preg_match_all to get an accurate count of how many times the pattern appears in the target).
$query="red";
$FileName = "search.txt";
foreach (explode(" ", strtolower(file_get_contents($FileName)) as $word) {
if (strtolower($query) == $word) {
$found = true;
break;
}
}
echo $found ? "Found" : "Not found";
Meh, a little less efficient, but it gets the job done.
Try this, splits the data at a space, and then sees if the query is in the array.
$query="red";
$FileName = "search.txt";
$fh = fopen($FileName, 'r') or die("Can't open file");
$data = fread($fh, filesize($FileName));
$items = explode(" ", $data);
$Pos = array_search ($query, $items);
if($Pos !== FALSE)
{
echo "Found";
}
else
{
echo "Not Found";
}
Try using strpos with " $query ", or use a regular expression and preg_match:
$query = "red";
if (strpos($data, " {$query} ") !== false) {
// data contains " red "
}
// OR
if (preg_match("/(^{$query}( )|( ){$query}( )|( ){$query}$)/", $data) === 1) {
// match found
}

Categories