PHP stristr issue - php

$bodytext = "we should see this text <more> but not this at all <html>";
if(stristr($bodytext, "<more>") == TRUE)
{
$find = "<more>";
$pos = stripos($bodytext, $find);
$bodytext = substr($bodytext, 0, $pos);
}
echo "$bodytext";
If the $bodytext contains other html code, this also causes the above code to return true :
<more
more>
How do I adjust my code so only (and exactly) :
<more>
returns true?

Simple/naiive:
$bodytext = preg_replace('/(.*?)<more>.*/', $1, $bodytext);

stristr returns all of the string from the match to the end of the string. If a match is not found, it returns false.
You therefore need to do this:
if(stristr($bodytext, "<more>") !== false) {
// match found
}
stripos is more suited to your needs:
$pos = stripos($bodytext, "<more>");
if($pos !== false) {
// match found
}
Alternative: See Marc B's answer, which does everything you appear to be trying to achieve in a single statement.

You could also use the explode function and output the first element of the array
$bodytext = "we should see this text <more> but not this at all <html>";
if(stristr($bodytext, "<more>") == TRUE)
{
$split = explode('<more>', $bodytext);
echo $split[0];
}

Related

How to trim string from right in PHP?

I have a string example
this-is-the-example/exa
I want to trim /exa from the above line
$string1 = "this-is-the-example/exa";
$string2 = "/exa";
I am using rtrim($string1, $sting2)
But the output is this-is-the-exampl
I want to this-is-the-example as output.
Both string are dynamic and may have multiple occurrences within the string. But I only want to remove the last part. Also its not compulsory that the string2 has / in it. this may be normal string too. like a, abc too..
There are various approaches you can use for this:
With substr(DEMO):
function removeFromEnd($haystack, $needle)
{
$length = strlen($needle);
if(substr($haystack, -$length) === $needle)
{
$haystack = substr($haystack, 0, -$length);
}
return $haystack;
}
$trim = '/exa';
$str = 'this-is-the-example/exa';
var_dump(removeFromEnd($str, $trim));
With regex(DEMO):
$trim = '/exa';
$str = 'this-is-the-example/exa';
function removeFromEnd($haystack, $needle)
{
$needle = preg_quote($needle, '/');
$haystack = preg_replace("/$needle$/", '', $haystack);
return $haystack;
}
var_dump(removeFromEnd($str, $trim));
First explode the string, remove last element from exploded array using array_pop, then implode it back again with /.
$str = "this-is-the-example/exa";
if(strpos($str, '/') !== false)
{
$arr = explode('/', $str);
array_pop($arr);
$str = implode('/', $arr);
// output this-is-the-example
}
This will work event if you have multiple / in the URL and will remove last element only.
$str = "this-is-the-example/somevalue/exa";
if(strpos($str, '/') !== false)
{
$arr = explode('/', $str);
array_pop($arr);
$str = implode('/', $arr);
// output this-is-the-example
}
Say hi to strstr()
$str = 'this-is-the-example/exa';
$trim = '/exa';
$result = strstr($str, $trim, true);
echo $result;
You can use explode
<?php
$x = "this-is-the-example/exa";
$y = explode('/', $x);
echo $y[0];
the second parameter of rtrim is a character mask and not a string, your last "e" is trimed and that's normal.
COnsider using something else, regexp for example (preg_replace) to fit your needs
This keeps everything before "/" char :
$str = preg_replace('/^([^\/]*).*/','$1', 'this-is-the-example/exa');
This removes the last part.
$str = preg_replace('/^(.*)\/.*$/','$1', 'this-is-the-example/exa/mple');
Hope this helps. :)
Simply try this code:
<?php
$this_example = substr("this-is-the-example/exa", 0, -4);
echo "<br/>".$this_example; // returns "this-is-the-example"
?>
To allow for error handling, if the substring is not found in the search string ...
<?php
$myString = 'this-is-the-example/exa';
//[Edit: see comment below] use strrpos, not strpos, to find the LAST occurrence
$endPosition = strrpos($myString, '/exa');
// TodO; if endPosition === False then handle error, substring not found
$leftPart = substr($myString, 0, $endPosition);
echo($leftPart);
?>
outputs
this-is-the-example

How can I remove the last part of a string?

This is my string:
monkey/rabbit/cat/donkey/duck
If my variable is cat...
$animal = cat
... I want to remove everything coming after cat.
My desired result is:
monkey/rabbit/cat
I tried to use str_replace:
$subject = 'monkey/rabbit/cat/donkey/duck';
$trimmed = str_replace($animal, '', $subject);
echo $trimmed;
But here I get the result:
monkey/rabbit//donkey/duck
So it is just cutting out cat.
You can combine strpos with substr:
$pos = strpos($subject, $animal);
if ($pos !== false) {
$result = substr($subject, 0, $pos + strlen($animal));
}
If you wold like to make sure it only the full segments are erased, in case of a partial match, you could use the offset argument of strpos:
$pos = strpos($subject, $animal);
if ($pos !== false) {
$result = substr($subject, 0, strpos($subject, '/', $pos));
}
You can use explode in your case:
$string = "monkey/rabbit/cat/donkey/duck";
$val = explode("donkey", $string );
echo $val[0];
Result: monkey/rabbit/cat
PS* Ofcourse there are better ways to do this
My approach would be to explode by your variable.
Take the first part and append the variable.
<?php
$string = 'monkey/rabbit/cat/donkey/duck';
$animal = 'cat';
$temp = explode($animal,$string);
print $temp[0] . $animal;
Will output nicely
monkey/rabbit/cat
There's no need to use any of strpos, strlen, substr or donkeys
<?php
$animal="cat";
$string1="monkey/rabbit/cat/donkey/duck";
$parts = explode($animal, $string1);
$res = $parts[0];
print("$res$animal")
?>
Here is a bit of explanation for what each step does:
$subject = 'monkey/rabbit/cat/donkey/duck';
$target = 'cat';
$target_length = strlen($target); // get the length of your target string
$target_index = strpos($subject, $target); // find the position of your target string
$new_length = $target_index + $target_length; // find the length of the new string
$new_subject = substr($subject, 0, $new_length); // trim to the new length using substr
echo $new_subject;
This can all be combined into one statement.
$new_subject = substr($subject, 0, strpos($subject, $target) + strlen($target));
This assumes your target is found. If the target is not found, the subject will be trimmed to the length of the target, which obviously is not what you want. For example, if your target string was "fish" the new subject would be "monk". This is why the other answer checks if ($pos !== false) {.
One of the comments on your question raises a valid point. If you search for a string that happens to be contained in one of the other strings, you may get unexpected results. There is really not a good way to avoid this problem when using the substr/strpos method. If you want to be sure to only match a complete word between your separators (/), you can explode by / and search for your target in the resulting array.
$subject = explode('/', $subject); // convert to array
$index = array_search($target, $subject); // find the target
if ($index !== false) { // if it is found,
$subject = array_slice($subject, 0, $index + 1); // remove the end of the array after it
}
$new_subject = implode('/', $subject); // convert back to string
I'm probably going to kop some flak for going down the RegExp route but...
$subject = 'monkey/rabbit/polecat/cat/catfish/duck';
$animal = "cat";
echo preg_replace('~(.*(?:/|^)' . preg_quote($animal) . ')(?:/|$).*~i', "$1", $subject);
This will ensure that your animal is wrapped immediately on either side with / characters, or that it's at the start or end of the string (i.e. monkey or duck).
So in this example it'll output:
monkey/rabbit/polecat/cat
Ending specifically with cat rather than stumbling at polecat or catfish

PHP Search for a string in remote webpage

I am trying to write a script with PHP where it'll open up a text file ./urls.txt and check each domain for a specific word. I am really new to PHP.
Example:
Look for the word "Hello" in the following domains.
List:
Domain1.LTD
Domain2.LTD
Domain3.LTD
and just simply print out domain name + valid/invalid.
<?PHP
$link = "http://yahoo.com"; //not sure how to loop to read each line from a file.
$linkcontents = file_get_contents($link);
$needle = "Hello";
if (strpos($linkcontents, $needle) == false) {
echo "Valid";
} else {
echo "Invalid";
}
?>
$arrayOfLinks = array(
"http://example.com/file.txt",
"https://www.example-site-2.com/files/file.txt"
);
$needle = "Hello";
foreach($arrayOfLinks as $link){ // loop through the array
$linkcontents = file_get_contents($link);
if (stripos($linkcontents , $needle) !== false) { // stripos is case-insensitive search
// the needle exists in $linkcontents
// !== false instead of != false since stripos can return 0 meaning the needle is the first word of the contents
echo "Valid";
} else {
// the word does not exist in the given text
echo "Invalid";
}
}
First of all use CURL in favor of file_get_contents() because of security.
This would be a correct strpos example:
//your previous code
if (strpos($linkcontents, $needle) !== false) { // see the !==
echo "Valid"; //Needle found
} else {
echo "Invalid"; //Needle not found
}
For more complex crawling you could use some regexp instead of strpos.

What is the correct return type of strpos? Searching for the '#' char

For example I have a string I am # the penthouse.
I need to know how to find the character "#" in php string and the position of the character.
I tried strpos but its not working.
Thanks for the help in advance.
EDIT:
I've been using this for get the character:
$text = "I am # the penthouse";
$pos = strrpos($text, '#');
if($pos == true)
{
echo "yes";
}
I would do this
Note, I'm using strpos, not reverse counterpart, strrpos
if (($pos = strpos('I am # the penthouse.', '#') !== false) {
echo "pos found: {$pos}";
}
else {
echo "no # found";
}
Note: Because # could be the first character in a string, strpos could return a 0. Consider the following:
// check twitter name for #
if (strpos('#twitter', '#')) { ... }
// resolves to
if (0) {
// this will never run!
}
So, strpos will explicitly return false when no match is found. This is how to properly check for a substring position:
// check twitter name for #
if (strpos('#twitter', '#') !== false) {
// valid twitter name
}
You can also use the function strpos() for that purpose. Like strrpos() it searches for a substring - or at least a char - in a string but it the returns the first position of that substring or boolean(false) if the substring was not found. So the snippet would look like:
$position = strpos('I am # the penthouse', '#');
if($position === FALSE) {
echo 'The # was not found';
} else {
echo 'The # was found at position ' . $position;
}
Note that there are common pitfalls that come with strpos() and strrpos() in php.
1 . Check Type of the return value!
Imagine the following example :
if(!strpos('#stackoverflow', '#')) {
echo 'the string contains no #';
}
The would output that '#' was not found although the string contains an '#'. Thats because of the weak data typing in PHP. The previous strpos() call will return int(0) because it is the first char in string. But unless you enforce a strict type check using the '===' operator this int(0) will be handle as FALSE. This is the correct way:
if(strpos('#stackoverflow', '#') === FALSE) {
echo 'the string contains no #';
}
2 . Use the correct order of arguments!
The signature of strpos is:
strpos($haystack, $needle [, $start]);
Thats unlike other str* functions in PHP where the $needle is the first arg.
Keep this in mind! ;)
This seems to be working for me in PHP 5.4.7:
$pos = strpos('I am # the penthouse', '#');
What do you mean exactly by strpos is not working?
Look this is working for me, it will also work for you
$string = "hello i am # your home";
echo strpos($string,"#");
i hope this will help -
<?php
$string = "I am # the penthouse";
$desired_char = "#";
// checking whether # present or not
if(strstr($string, $desired_char)){
// the position of the character
$position = strpos('I am # the penthouse', $desired_char);
echo $position;
}
else echo $desired_char." Not found!";
?>

Check and get the text after "near " in php

When someone writes:
"Near Tokyo"
I would like to check first if the $search contains "near" and if it does then take the "Tokyo" into a variable $location.
I tried this:
if(strpos($search, 'near') == true){
$search = explode("near ", $location);
echo $location;
exit();
}
did not work, it does not execute the if statement
You have multiple bugs here:
strpos may return 0, which signifies a match but will not compare equal to true
strpos is case-sensitive, which would make your example not work (look into stripos instead)
explode is also case-sensitive
It would probably be easiest to use a regex for this:
$input = "Near Tokyo";
if (preg_match('/near\s+(\w+)/i', $input, $matches)) {
echo "Near: ".$matches[1]."\n";
}
else {
echo "No match.\n";
}
See it in action.
This particular regex will only match the next word after "near", but this can be modified to suit your requirements.
returntype of strpos is int, not bool
http://php.net/manual/en/function.strpos.php
so use (according to manual pages) this:
if(strpos($search, 'near') !== false)
change it to:
if(strpos($search, 'near') !== false){
$search = explode("near ", $location);
echo $location;
exit();
}
just take a look at the documentation where this behaviour is explained:
It is easy to mistake the return values for "character found at
position 0" and "character not found". Here's how to detect the
difference:
<?php
$pos = strrpos($mystring, "b");
if ($pos === false) { // note: three equal signs
// not found...
}
?>
Yes, strpos, cumbersome boolean result handling. You probably should or should want to use stristr instead, which is also case-insensitive:
if (stristr($search, "Near")) {
And since you are extracting text anyway, why not use a regex? (People are using the awful explode workaround way too often.)
if (preg_match("'Near (\S+)'i", $search, $match)) {
echo $match[1];
}
use this to get a result:
if(strpos($search, 'near') !== false){
$location = explode("near ", $search);
print_r($location);
exit();
}
$search = "Near Tokyo";
if(strpos($search, 'Near') === 0){
$location = explode("Near ", $search);
echo $location[1];
exit();
}
<?php
$search = "Near Tokoyo";
if(preg_match("/near ([a-z]+)/i", $search, $match))
{
$location = $match[1];
echo $location;
}
?>
EDIT:
Fixed some bugs in your code.
if(stripos($search, 'near') !== false){
$location = explode("near ", $search);
echo $location[0];
exit();
}

Categories