Truncate text to a desired end word - php

So I want to truncate a very long text but the problem is that I don't want x number of word or characters. I want the text truncated when it reaches a special string like ###end### or something similar e.g. I want to set where exactly it ends.
edit: I know how to check the existences of the string I wasn't sure how to make the truncation

Maybe something like:
$pos = strpos($mystring, "###end###");
$finalText = substr ( $mystring , 0 , $pos );

This can be done with a single call. My answer assumes that the targeted substring will exist in the string.
Code: (Demo)
$string='Here is a sample string.###end### I do not want to see any of this';
echo strstr($string,'###end###',true); // 3rd parameter 'true' will extract everything before
Output:
Here is a sample string.
If you are uncertain if the substring will exist (and if it doesn't, you want the fullstring) this is a reliable method:
Code: (Demo)
$string='Here is a sample string.###end### I do not want to see any of this';
echo explode('###end###',$string,2)[0]; // 3rd parameter 2 will limit the number of elements produced to two
Output:
Here is a sample string.

Related

PHP Compare two strings and display the difference while preserving their original character positions

For this I have been trying things myself and trying to find answers online for a while now. What I would like to achieve, is to compare two strings and display the difference in characters as an integer, whilst preserving the character positions. Basically, I have a question and answer app, and I need to compare the correct answer to the given answer. So, for example:
$correct = 'Monday';
$answer = 'Manday';
In the above example there is only one error made, so when comparing the $correct and $answer strings, I need to display "1".
I tried using strcmp, but that is not giving me the correct results. For the above example, doing strcmp($original, $answer) would give me this result: 3584.
Also when using similar_text I do not get the results I need. Example, when using similar_text($original,$answer), while using the above Monday and Manday example, it gives an expected result of 5 characters that are similar, out of 6. But when I do the following, it still gives me 1 as a result, while it should be 0 (for my case):
similar_text("Hello", "World") // The "o" is matched, but it is in the wrong position
So, in short, what I need to achieve is this. I have a correct answer, and a user input given answer. I want to compare the user given answer against the original correct answer. And how do I want to compare them? I want to compare each character position from both strings, and for all characters that are incorrect, I want to return the total wrong characters as an integer.
Some more examples:
$str1 = 'Monday';
$str2 = 'Mondayy';
The above should return '1', because the second string has an extra character. So 1 error in total.
$str1 = 'Monday';
$str2 = 'Manday';
The above should return '1', because the second string has a one wrong character. So 1 error in total.
$str1 = 'Hello';
$str2 = 'World';
The above should return '5', because the second string does not match any of the first string's characters in their position. So 5 errors in total.
You want to use levenshtein() instead of similar_text()
similar_text() just calculates the longest matching substring. levenshtein() calculates how many characters have to be replaced to match the answer.
https://www.php.net/manual/en/function.levenshtein.php

How to refer to the second occurrence of a string in php?

I've been trying to replace my second occurrence for a certain character
For Example:
Hey, I'm trying something With PHP, Is it Working?
I need to get the position of the second comma, I've tried to use strpos but in vain because it's define that it finds the first occurrence of a string so I got Position: 3, any one knows a solution?
The strpos function accepts an optional third parameter which is an offset from which the search for the target string should begin. In this case, you may pass a call to strpos which finds the first index of comma, incremented by one, to find the second comma.
$input = "Hey, I'm trying something With PHP, Is it Working?";
echo strpos($input, ",", strpos($input, ",") + 1); // prints 34
Just for completeness/fun, we could also use a regex substring based approach here, and match the substring up the second comma:
$input = "Hey, I'm trying something With PHP, Is it Working?";
preg_match("/^[^,]*,[^,]*,/", $input, $matches);
echo strlen($matches[0]) - 1; // also prints 34
I know this has been already answered, but a more generic solution to find the last occurrence is to use strrpos.
strrpos accepts a third parameter that can be negative (contrary to strpos).
If negative, the search is performed right to left skipping the last offset bytes of the haystack and searching for the first occurrence of needle.
$foo = "0123456789a123456789b123456789c";
// Looking for '7' right to left from the 5th byte from the end
var_dump(strrpos($foo, '7', -5));

PHP - know characters failed in a preg_match function

There is a method to know which characters does not match a preg_match function?
For example:
preg_match('/^[a-z]*$/i', 'Hello World!');
Is there some function to know the incorrect char, in this case spance and "!"?
Thanks for your replies, but the problem in your examples is you don't indicate the begin and the end of the string. Your examples works with string contained in another one and not with the string that is exactly like I defined in the pattern.
For example, if I had to validate the italian fiscal code of a subject, composed by a string formatted like this:
XXX XXX YY X YY X YYY X (X = letter, Y = number - without spaces)
which pattern is:
'/^[A-Z]{6}[0-9]{2}[A-Z]{1}[0-9]{2}[A-Z]{1}[0-9]{3}[A-Z]{1}$/i'
I must validate the string that match exactly what I defined in the pattern.
If I use your code and I wrong 1 (only 1) character, the whole string was returned as error.
http://eval.in/9178
The problem of the reverse pattern occurs in a complex pattern, where are inserted the AND or the OR.
What I want to know is why the preg_match fails and not only if it fails or not.
Have you tried something like this?
$nonMatchingCharacters = preg_replace('/[a-z]/', '', $wholeString);
That should strip out the 'legal' characters, leaving only the ones that you want to mention in your validation error message.
You could also do other treatments like...
$nonMatchingCharactersArray = array_unique(explode('', $nonMatchingCharacters));
...if you want an array of unique, non-matching characters, and not just a string with bits stripped out of it.
That will indicate you the space and !
preg_match_all('/[^a-z]/i', 'Hello World!', $matches);
var_dump($matches);
http://eval.in/9132
Just remove everything that matches with preg_replace, then split into an array what remains.
<?php
$str = preg_replace('/([0-9]{2}[a-z]*)/i', '', '03Hello 02World!');
$characters = str_split($str);
var_dump($characters);
http://eval.in/9152

How to split a string and find the occurence of one string in another?

I need to figure out how to do some C# code in php, and im not sure exactly how.
so first off i need the Split function, im going to have a string like
"identifier 82asdjka271akshjd18ajjd"
and i need to split the identifier word from the rest. so in C#, i used string.Split(new char{' '}); or something like that (working off the top of my head) and got two strings, the first word, and then the second part.. i understand that the php split function has been deprecated as of PHP 5.3.0.. so thats not an option, what are the alternatives?
and im also looking for a IndexOf function, so if i had the above code again as an example, i would need the location of 271 in the string, so i can generate a substring.
you can use explode for splitting and strpos for finding the index of one string inside another.
$a = "identifier 82asdjka271akshjd18ajjd";
$arr = explode(' ',$a); // split on space..to get an array of size 2.
$pos = strpos($arr[1],'271'); // search for '271' in the 2nd ele of array.
echo $pos; // prints 8

Retain case when using str_ireplace?

I am building a search that will wrap the searched text with a <span> tag and I have this code working OK:
str_ireplace($q,'<span>'.$q.'</span>',$row[name]);
The problem is, if a user searches for Tom is will show Tom which is cool, but if they put in tom because of the str_ireplace it would show tom, does that make sense? The real issue is if someone entered tOm aRnFeLd although it would search OK, the aesthetics would actually show up on the page tOm aRnFeLd
How can I retain the capital letters and lower case 'ness of both strings? Is there a better way to wrap case insensitive text from a string?
use stristr to get the needle from the haystack, case insensitive
$keyword_caseRetained_all = stristr($excerpt, $keyword);
but that returns the needle and the rest of haystack too, so you have to use substr to only keep the needle portion. start at position 0, get up to the length of keyword
$keyword_caseRetained = substr($keyword_caseRetained_all, 0, strlen($keyword) );
now use that variable inside the str_ireplace function
$excerpt = str_ireplace($keyword, '<em>'.$keyword_caseRetained.'</em>', $excerpt);
once you know this, you can combine lines 1 and 2 in a nice rats nest to shorten your code.
or add this as a method to a string manipulation class.
Get phrase length strlen()
Find occurrence of phrase using stripos()
Insert into text <span> after text's N character (where N is result from point #2)
Insert into text </span> after text's N+M character (where N is result from point #2 and M is result from point #1)
Continue points 2-4 (Using third parameter of strpos() - offset)

Categories