Related
How can I truncate a string after 20 words in PHP?
function limit_text($text, $limit) {
if (str_word_count($text, 0) > $limit) {
$words = str_word_count($text, 2);
$pos = array_keys($words);
$text = substr($text, 0, $pos[$limit]) . '...';
}
return $text;
}
echo limit_text('Hello here is a long sentence that will be truncated by the', 5);
Outputs:
Hello here is a long ...
Change the number 3 to the number 20 below to get the first 20 words, or pass it as parameter. The following demonstrates how to get the first 3 words: (so change the 3 to 20 to change the default value):
function first3words($s, $limit=3) {
return preg_replace('/((\w+\W*){'.($limit-1).'}(\w+))(.*)/', '${1}', $s);
}
var_dump(first3words("hello yes, world wah ha ha")); # => "hello yes, world"
var_dump(first3words("hello yes,world wah ha ha")); # => "hello yes,world"
var_dump(first3words("hello yes world wah ha ha")); # => "hello yes world"
var_dump(first3words("hello yes world")); # => "hello yes world"
var_dump(first3words("hello yes world.")); # => "hello yes world"
var_dump(first3words("hello yes")); # => "hello yes"
var_dump(first3words("hello")); # => "hello"
var_dump(first3words("a")); # => "a"
var_dump(first3words("")); # => ""
To Nearest Space
Truncates to nearest preceding space of target character. Demo
$str The string to be truncated
$chars The amount of characters to be stripped, can be overridden by $to_space
$to_space boolean for whether or not to truncate from space near $chars limit
Function
function truncateString($str, $chars, $to_space, $replacement="...") {
if($chars > strlen($str)) return $str;
$str = substr($str, 0, $chars);
$space_pos = strrpos($str, " ");
if($to_space && $space_pos >= 0)
$str = substr($str, 0, strrpos($str, " "));
return($str . $replacement);
}
Sample
<?php
$str = "this is a string that is just some text for you to test with";
print(truncateString($str, 20, false) . "\n");
print(truncateString($str, 22, false) . "\n");
print(truncateString($str, 24, true) . "\n");
print(truncateString($str, 26, true, " :)") . "\n");
print(truncateString($str, 28, true, "--") . "\n");
?>
Output
this is a string tha...
this is a string that ...
this is a string that...
this is a string that is :)
this is a string that is--
use explode() .
Example from the docs.
// Example 1
$pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2
note that explode has a limit function. So you could do something like
$message = implode(" ", explode(" ", $long_message, 20));
Try regex.
You need something that would match 20 words (or 20 word boundaries).
So (my regex is terrible so correct me if this isn't accurate):
/(\w+\b){20}/
And here are some examples of regex in php.
Simple and fully equiped truncate() method:
function truncate($string, $width, $etc = ' ..')
{
$wrapped = explode('$trun$', wordwrap($string, $width, '$trun$', false), 2);
return $wrapped[0] . (isset($wrapped[1]) ? $etc : '');
}
Its not my own creation, its a modification of previous posts. credits goes to karim79.
function limit_text($text, $limit) {
$strings = $text;
if (strlen($text) > $limit) {
$words = str_word_count($text, 2);
$pos = array_keys($words);
if(sizeof($pos) >$limit)
{
$text = substr($text, 0, $pos[$limit]) . '...';
}
return $text;
}
return $text;
}
If you code on Laravel just use Illuminate\Support\Str
here is example
Str::words($category->publication->title, env('WORDS_COUNT_HOME'), '...')
Hope this was helpful.
Split the string (into an array) by <space>, and then take the first 20 elements of that array.
With triple dots:
function limitWords($text, $limit) {
$word_arr = explode(" ", $text);
if (count($word_arr) > $limit) {
$words = implode(" ", array_slice($word_arr , 0, $limit) ) . ' ...';
return $words;
}
return $text;
}
Try below code,
$text = implode(' ', array_slice(explode(' ', $text), 0, 32))
echo $text;
Something like this could probably do the trick:
<?php
$words = implode(' ', array_slice(split($input, ' ', 21), 0, 20));
use PHP tokenizer function strtok() in a loop.
$token = strtok($string, " "); // we assume that words are separated by sapce or tab
$i = 0;
$first20Words = '';
while ($token !== false && $i < 20) {
$first20Words .= $token;
$token = strtok(" ");
$i++;
}
echo $first20Words;
based on 動靜能量's answer:
function truncate_words($string,$words=20) {
return preg_replace('/((\w+\W*){'.($words-1).'}(\w+))(.*)/', '${1}', $string);
}
or
function truncate_words_with_ellipsis($string,$words=20,$ellipsis=' ...') {
$new = preg_replace('/((\w+\W*){'.($words-1).'}(\w+))(.*)/', '${1}', $string);
if($new != $string){
return $new.$ellipsis;
}else{
return $string;
}
}
This worked me for UNICODE (UTF8) sentences too:
function myUTF8truncate($string, $width){
if (mb_str_word_count($string) > $width) {
$string= preg_replace('/((\w+\W*|| [\p{L}]+\W*){'.($width-1).'}(\w+))(.*)/', '${1}', $string);
}
return $string;
}
Here is what I have implemented.
function summaryMode($text, $limit, $link) {
if (str_word_count($text, 0) > $limit) {
$numwords = str_word_count($text, 2);
$pos = array_keys($numwords);
$text = substr($text, 0, $pos[$limit]).'... Read More';
}
return $text;
}
As you can see it is based off karim79's answer, all that needed changing was that the if statement also needed to check against words not characters.
I also added a link to main function for convenience. So far it hsa worked flawlessly. Thanks to the original solution provider.
Here's one I use:
$truncate = function( $str, $length ) {
if( strlen( $str ) > $length && false !== strpos( $str, ' ' ) ) {
$str = preg_split( '/ [^ ]*$/', substr( $str, 0, $length ));
return htmlspecialchars($str[0]) . '…';
} else {
return htmlspecialchars($str);
}
};
return $truncate( $myStr, 50 );
Another solution :)
$aContent = explode(' ', $cContent);
$cContent = '';
$nCount = count($aContent);
for($nI = 0; ($nI < 20 && $nI < $nCount); $nI++) {
$cContent .= $aContent[$nI] . ' ';
}
trim($cContent, ' ');
echo '<p>' . $cContent . '</p>';
To limit words, am using the following little code :
$string = "hello world ! I love chocolate.";
$explode = array_slice(explode(' ', $string), 0, 4);
$implode = implode(" ",$explode);
echo $implode;
$implot will give : hello world ! I
function getShortString($string,$wordCount,$etc = true)
{
$expString = explode(' ',$string);
$wordsInString = count($expString);
if($wordsInString >= $wordCount )
{
$shortText = '';
for($i=0; $i < $wordCount-1; $i++)
{
$shortText .= $expString[$i].' ';
}
return $etc ? $shortText.='...' : $shortText;
}
else return $string;
}
Simpler than all previously posted regex techniques, just match the first n sequences of non-word followed by sequences of word characters. Making the non-word characters optional allows matching of word characters from the start of the string. Greedy word character matching ensures that consecutive word characters are never treated as individual words.
By writing \K in the pattern after matching n substrings, then matching the rest of the string (add the s pattern modifier if you need dots to match newlines), the replacement can be an empty string.
Code: (Demo)
function firstNWords(string $string, int $limit = 3) {
return preg_replace("/(?:\W*\w+){{$limit}}\K.*/", '', $string);
}
Lets assume we have the string variables $string, $start, and $limit we can borrow 3 or 4 functions from PHP to achieve this. They are:
script_tags() PHP function to remove the unnecessary HTML and PHP
tags (if there are any). This wont be necessary, if there are no HTML or PHP tags.
explode() to split the $string into an array
array_splice() to specify the number of words and where it'll start
from. It'll be controlled by vallues assigned to our $start and $limit variables.
and finally, implode() to join the array elements into your truncated
string..
function truncateString($string, $start, $limit){
$stripped_string =strip_tags($string); // if there are HTML or PHP tags
$string_array =explode(' ',$stripped_string);
$truncated_array = array_splice($string_array,$start,$limit);
$truncated_string=implode(' ',$truncated_array);
return $truncated_string;
}
It's that simple..
I hope this was helpful.
I made my function:
function summery($text, $limit) {
$words=preg_split('/\s+/', $text);
$count=count(preg_split('/\s+/', $text));
if ($count > $limit) {
$text=NULL;
for($i=0;$i<$limit;$i++)
$text.=$words[$i].' ';
$text.='...';
}
return $text;
}
function limitText($string,$limit){
if(strlen($string) > $limit){
$string = substr($string, 0,$limit) . "...";
}
return $string;
}
this will return 20 words. I hope it will help
$text='some text';
$len=strlen($text);
$limit=500;
// char
if($len>$limit){
$text=substr($text,0,$limit);
$words=explode(" ", $text);
$wcount=count($words);
$ll=strlen($words[$wcount]);
$text=substr($text,0,($limit-$ll+1)).'...';
}
function wordLimit($str, $limit) {
$arr = explode(' ', $str);
if(count($arr) <= $limit){
return $str;
}
$result = '';
for($i = 0; $i < $limit; $i++){
$result .= $arr[$i].' ';
}
return trim($result);
}
echo wordLimit('Hello Word', 1); // Hello
echo wordLimit('Hello Word', 2); // Hello Word
echo wordLimit('Hello Word', 3); // Hello Word
echo wordLimit('Hello Word', 0); // ''
I would go with explode() , array_pop() and implode(), eg.:
$long_message = "I like summer, also I like winter and cats, btw dogs too!";
$trimmed_message = explode(" ", $long_message, 5); // <-- '5' means 4 words to be returned
array_pop($trimmed_message); //removing last element from exploded array
$trimmed_message = implode(" ", $trimmed_message) . '...';
Result:
I like summer, also...
what about
chunk_split($str,20);
Entry in the PHP Manual
function limit_word($start,$limit,$text){
$limit=$limit-1;
$stripped_string =strip_tags($text);
$string_array =explode(' ',$stripped_string);
if(count($string_array)>$limit){
$truncated_array = array_splice($string_array,$start,$limit);
$text=implode(' ',$truncated_array).'...';
return($text);
}
else{return($text);}
}
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
I need a function that returns the substring between two words (or two characters).
I'm wondering whether there is a php function that achieves that. I do not want to think about regex (well, I could do one but really don't think it's the best way to go). Thinking of strpos and substr functions.
Here's an example:
$string = "foo I wanna a cake foo";
We call the function: $substring = getInnerSubstring($string,"foo");
It returns: " I wanna a cake ".
Update:
Well, till now, I can just get a substring beteen two words in just one string, do you permit to let me go a bit farther and ask if I can extend the use of getInnerSubstring($str,$delim) to get any strings that are between delim value, example:
$string =" foo I like php foo, but foo I also like asp foo, foo I feel hero foo";
I get an array like {"I like php", "I also like asp", "I feel hero"}.
If the strings are different (ie: [foo] & [/foo]), take a look at this post from Justin Cook.
I copy his code below:
function get_string_between($string, $start, $end){
$string = ' ' . $string;
$ini = strpos($string, $start);
if ($ini == 0) return '';
$ini += strlen($start);
$len = strpos($string, $end, $ini) - $ini;
return substr($string, $ini, $len);
}
$fullstring = 'this is my [tag]dog[/tag]';
$parsed = get_string_between($fullstring, '[tag]', '[/tag]');
echo $parsed; // (result = dog)
Regular expressions is the way to go:
$str = 'before-str-after';
if (preg_match('/before-(.*?)-after/', $str, $match) == 1) {
echo $match[1];
}
onlinePhp
function getBetween($string, $start = "", $end = ""){
if (strpos($string, $start)) { // required if $start not exist in $string
$startCharCount = strpos($string, $start) + strlen($start);
$firstSubStr = substr($string, $startCharCount, strlen($string));
$endCharCount = strpos($firstSubStr, $end);
if ($endCharCount == 0) {
$endCharCount = strlen($firstSubStr);
}
return substr($firstSubStr, 0, $endCharCount);
} else {
return '';
}
}
Sample use:
echo getBetween("abc","a","c"); // returns: 'b'
echo getBetween("hello","h","o"); // returns: 'ell'
echo getBetween("World","a","r"); // returns: ''
use strstr php function twice.
$value = "This is a great day to be alive";
$value = strstr($value, "is"); //gets all text from needle on
$value = strstr($value, "be", true); //gets all text before needle
echo $value;
outputs:
"is a great day to"
function getInnerSubstring($string,$delim){
// "foo a foo" becomes: array(""," a ","")
$string = explode($delim, $string, 3); // also, we only need 2 items at most
// we check whether the 2nd is set and return it, otherwise we return an empty string
return isset($string[1]) ? $string[1] : '';
}
Example of use:
var_dump(getInnerSubstring('foo Hello world foo','foo'));
// prints: string(13) " Hello world "
If you want to remove surrounding whitespace, use trim. Example:
var_dump(trim(getInnerSubstring('foo Hello world foo','foo')));
// prints: string(11) "Hello world"
function getInbetweenStrings($start, $end, $str){
$matches = array();
$regex = "/$start([a-zA-Z0-9_]*)$end/";
preg_match_all($regex, $str, $matches);
return $matches[1];
}
for examle you want the array of strings(keys) between ## in following
example, where '/' doesn't fall in-between
$str = "C://##ad_custom_attr1##/##upn##/##samaccountname##";
$str_arr = getInbetweenStrings('##', '##', $str);
print_r($str_arr);
I like the regular expression solutions but none of the others suit me.
If you know there is only gonna be 1 result you can use the following:
$between = preg_replace('/(.*)BEFORE(.*)AFTER(.*)/s', '\2', $string);
Change BEFORE and AFTER to the desired delimiters.
Also keep in mind this function will return the whole string in case nothing matched.
This solution is multiline but you can play with the modifiers depending on your needs.
Not a php pro. but i recently ran into this wall too and this is what i came up with.
function tag_contents($string, $tag_open, $tag_close){
foreach (explode($tag_open, $string) as $key => $value) {
if(strpos($value, $tag_close) !== FALSE){
$result[] = substr($value, 0, strpos($value, $tag_close));;
}
}
return $result;
}
$string = "i love cute animals, like [animal]cat[/animal],
[animal]dog[/animal] and [animal]panda[/animal]!!!";
echo "<pre>";
print_r(tag_contents($string , "[animal]" , "[/animal]"));
echo "</pre>";
//result
Array
(
[0] => cat
[1] => dog
[2] => panda
)
A vast majority of answers here don't answer the edited part, I guess they were added before. It can be done with regex, as one answer mentions. I had a different approach.
This function searches $string and finds the first string between $start and $end strings, starting at $offset position. It then updates the $offset position to point to the start of the result. If $includeDelimiters is true, it includes the delimiters in the result.
If the $start or $end string are not found, it returns null. It also returns null if $string, $start, or $end are an empty string.
function str_between(string $string, string $start, string $end, bool $includeDelimiters = false, int &$offset = 0): ?string
{
if ($string === '' || $start === '' || $end === '') return null;
$startLength = strlen($start);
$endLength = strlen($end);
$startPos = strpos($string, $start, $offset);
if ($startPos === false) return null;
$endPos = strpos($string, $end, $startPos + $startLength);
if ($endPos === false) return null;
$length = $endPos - $startPos + ($includeDelimiters ? $endLength : -$startLength);
if (!$length) return '';
$offset = $startPos + ($includeDelimiters ? 0 : $startLength);
$result = substr($string, $offset, $length);
return ($result !== false ? $result : null);
}
The following function finds all strings that are between two strings (no overlaps). It requires the previous function, and the arguments are the same. After execution, $offset points to the start of the last found result string.
function str_between_all(string $string, string $start, string $end, bool $includeDelimiters = false, int &$offset = 0): ?array
{
$strings = [];
$length = strlen($string);
while ($offset < $length)
{
$found = str_between($string, $start, $end, $includeDelimiters, $offset);
if ($found === null) break;
$strings[] = $found;
$offset += strlen($includeDelimiters ? $found : $start . $found . $end); // move offset to the end of the newfound string
}
return $strings;
}
Examples:
str_between_all('foo 1 bar 2 foo 3 bar', 'foo', 'bar') gives [' 1 ', ' 3 '].
str_between_all('foo 1 bar 2', 'foo', 'bar') gives [' 1 '].
str_between_all('foo 1 foo 2 foo 3 foo', 'foo', 'foo') gives [' 1 ', ' 3 '].
str_between_all('foo 1 bar', 'foo', 'foo') gives [].
If you're using foo as a delimiter, then look at explode()
<?php
function getBetween($content,$start,$end){
$r = explode($start, $content);
if (isset($r[1])){
$r = explode($end, $r[1]);
return $r[0];
}
return '';
}
?>
Example:
<?php
$content = "Try to find the guy in the middle with this function!";
$start = "Try to find ";
$end = " with this function!";
$output = getBetween($content,$start,$end);
echo $output;
?>
This will return "the guy in the middle".
Simple, short, and sweet. It's up to you to make any enhancements.
function getStringBetween($str, $start, $end)
{
$pos1 = strpos($str, $start);
$pos2 = strpos($str, $end);
return substr($str, $pos1+1, $pos2-($pos1+1));
}
If you have multiple recurrences from a single string and you have different [start] and [\end] pattern.
Here's a function which output an array.
function get_string_between($string, $start, $end){
$split_string = explode($end,$string);
foreach($split_string as $data) {
$str_pos = strpos($data,$start);
$last_pos = strlen($data);
$capture_len = $last_pos - $str_pos;
$return[] = substr($data,$str_pos+1,$capture_len);
}
return $return;
}
Here's a function
function getInnerSubstring($string, $boundstring, $trimit=false) {
$res = false;
$bstart = strpos($string, $boundstring);
if ($bstart >= 0) {
$bend = strrpos($string, $boundstring);
if ($bend >= 0 && $bend > $bstart)
$res = substr($string, $bstart+strlen($boundstring), $bend-$bstart-strlen($boundstring));
}
return $trimit ? trim($res) : $res;
}
Use it like
$string = "foo I wanna a cake foo";
$substring = getInnerSubstring($string, "foo");
echo $substring;
Output (note that it returns spaces in front and at the and of your string if exist)
I wanna a cake
If you want to trim result use function like
$substring = getInnerSubstring($string, "foo", true);
Result: This function will return false if $boundstring was not found in $string or if $boundstring exists only once in $string, otherwise it returns substring between first and last occurrence of $boundstring in $string.
References
strpos()
strrpos()
substr()
trim()
Improvement of Alejandro's answer. You can leave the $start or $end arguments empty and it will use the start or end of the string.
echo get_string_between("Hello my name is bob", "my", ""); //output: " name is bob"
private function get_string_between($string, $start, $end){ // Get
if($start != ''){ //If $start is empty, use start of the string
$string = ' ' . $string;
$ini = strpos($string, $start);
if ($ini == 0) return '';
$ini += strlen($start);
}
else{
$ini = 0;
}
if ($end == '') { //If $end is blank, use end of string
return substr($string, $ini);
}
else{
$len = strpos($string, $end, $ini) - $ini; //Work out length of string
return substr($string, $ini, $len);
}
}
private function getStringBetween(string $from, string $to, string $haystack): string
{
$fromPosition = strpos($haystack, $from) + strlen($from);
$toPosition = strpos($haystack, $to, $fromPosition);
$betweenLength = $toPosition - $fromPosition;
return substr($haystack, $fromPosition, $betweenLength);
}
Use:
<?php
$str = "...server daemon started with pid=6849 (parent=6848).";
$from = "pid=";
$to = "(";
echo getStringBetween($str,$from,$to);
function getStringBetween($str,$from,$to)
{
$sub = substr($str, strpos($str,$from)+strlen($from),strlen($str));
return substr($sub,0,strpos($sub,$to));
}
?>
A bit improved code from GarciaWebDev and Henry Wang. If empty $start or $end is given, function returns values from the beginning or to the end of the $string. Also Inclusive option is available, whether we want to include search result or not:
function get_string_between ($string, $start, $end, $inclusive = false){
$string = " ".$string;
if ($start == "") { $ini = 0; }
else { $ini = strpos($string, $start); }
if ($end == "") { $len = strlen($string); }
else { $len = strpos($string, $end, $ini) - $ini;}
if (!$inclusive) { $ini += strlen($start); }
else { $len += strlen($end); }
return substr($string, $ini, $len);
}
I have to add something to the post of Julius Tilvikas. I looked for a solution like this one he described in his post. But i think there is a mistake. I don't get realy the string between two string, i also get more with this solution, because i have to substract the lenght of the start-string. When do this, i realy get the String between two strings.
Here are my changes of his solution:
function get_string_between ($string, $start, $end, $inclusive = false){
$string = " ".$string;
if ($start == "") { $ini = 0; }
else { $ini = strpos($string, $start); }
if ($end == "") { $len = strlen($string); }
else { $len = strpos($string, $end, $ini) - $ini - strlen($start);}
if (!$inclusive) { $ini += strlen($start); }
else { $len += strlen($end); }
return substr($string, $ini, $len);
}
Greetz
V
Try this, Its work for me, get data between test word.
$str = "Xdata test HD01 test 1data";
$result = explode('test',$str);
print_r($result);
echo $result[1];
In PHP's strpos style this will return false if the start mark sm or the end mark em are not found.
This result (false) is different from an empty string that is what you get if there is nothing between the start and end marks.
function between( $str, $sm, $em )
{
$s = strpos( $str, $sm );
if( $s === false ) return false;
$s += strlen( $sm );
$e = strpos( $str, $em, $s );
if( $e === false ) return false;
return substr( $str, $s, $e - $s );
}
The function will return only the first match.
It's obvious but worth mentioning that the function will first look for sm and then for em.
This implies you may not get the desired result/behaviour if em has to be searched first and then the string have to be parsed backward in search of sm.
This is the function I'm using for this. I combined two answers in one function for single or multiple delimiters.
function getStringBetweenDelimiters($p_string, $p_from, $p_to, $p_multiple=false){
//checking for valid main string
if (strlen($p_string) > 0) {
//checking for multiple strings
if ($p_multiple) {
// getting list of results by end delimiter
$result_list = explode($p_to, $p_string);
//looping through result list array
foreach ( $result_list AS $rlkey => $rlrow) {
// getting result start position
$result_start_pos = strpos($rlrow, $p_from);
// calculating result length
$result_len = strlen($rlrow) - $result_start_pos;
// return only valid rows
if ($result_start_pos > 0) {
// cleanying result string + removing $p_from text from result
$result[] = substr($rlrow, $result_start_pos + strlen($p_from), $result_len);
}// end if
} // end foreach
// if single string
} else {
// result start point + removing $p_from text from result
$result_start_pos = strpos($p_string, $p_from) + strlen($p_from);
// lenght of result string
$result_length = strpos($p_string, $p_to, $result_start_pos);
// cleaning result string
$result = substr($p_string, $result_start_pos+1, $result_length );
} // end if else
// if empty main string
} else {
$result = false;
} // end if else
return $result;
} // end func. get string between
For simple use (returns two):
$result = getStringBetweenDelimiters(" one two three ", 'one', 'three');
For getting each row in a table to result array :
$result = getStringBetweenDelimiters($table, '<tr>', '</tr>', true);
an edited version of what Alejandro García Iglesias put.
This allows you to pick a specific location of the string you want to get based on the number of times the result is found.
function get_string_between_pos($string, $start, $end, $pos){
$cPos = 0;
$ini = 0;
$result = '';
for($i = 0; $i < $pos; $i++){
$ini = strpos($string, $start, $cPos);
if ($ini == 0) return '';
$ini += strlen($start);
$len = strpos($string, $end, $ini) - $ini;
$result = substr($string, $ini, $len);
$cPos = $ini + $len;
}
return $result;
}
usage:
$text = 'string has start test 1 end and start test 2 end and start test 3 end to print';
//get $result = "test 1"
$result = $this->get_string_between_pos($text, 'start', 'end', 1);
//get $result = "test 2"
$result = $this->get_string_between_pos($text, 'start', 'end', 2);
//get $result = "test 3"
$result = $this->get_string_between_pos($text, 'start', 'end', 3);
strpos has an additional optional input to start its search at a specific point. so I store the previous position in $cPos so when the for loop checks again, it starts at the end of where it left off.
easy solution using substr
$posStart = stripos($string, $start) + strlen($start);
$length = stripos($string, $end) - $posStart;
$substring = substr($string, $posStart, $length);
Use:
function getdatabetween($string, $start, $end){
$sp = strpos($string, $start)+strlen($start);
$ep = strpos($string, $end)-strlen($start);
$data = trim(substr($string, $sp, $ep));
return trim($data);
}
$dt = "Find string between two strings in PHP";
echo getdatabetween($dt, 'Find', 'in PHP');
I had some problems with the get_string_between() function, used here. So I came with my own version. Maybe it could help people in the same case as mine.
protected function string_between($string, $start, $end, $inclusive = false) {
$fragments = explode($start, $string, 2);
if (isset($fragments[1])) {
$fragments = explode($end, $fragments[1], 2);
if ($inclusive) {
return $start.$fragments[0].$end;
} else {
return $fragments[0];
}
}
return false;
}
wrote these some time back, found it very useful for a wide range of applications.
<?php
// substr_getbykeys() - Returns everything in a source string that exists between the first occurance of each of the two key substrings
// - only returns first match, and can be used in loops to iterate through large datasets
// - arg 1 is the first substring to look for
// - arg 2 is the second substring to look for
// - arg 3 is the source string the search is performed on.
// - arg 4 is boolean and allows you to determine if returned result should include the search keys.
// - arg 5 is boolean and can be used to determine whether search should be case-sensative or not.
//
function substr_getbykeys($key1, $key2, $source, $returnkeys, $casematters) {
if ($casematters === true) {
$start = strpos($source, $key1);
$end = strpos($source, $key2);
} else {
$start = stripos($source, $key1);
$end = stripos($source, $key2);
}
if ($start === false || $end === false) { return false; }
if ($start > $end) {
$temp = $start;
$start = $end;
$end = $temp;
}
if ( $returnkeys === true) {
$length = ($end + strlen($key2)) - $start;
} else {
$start = $start + strlen($key1);
$length = $end - $start;
}
return substr($source, $start, $length);
}
// substr_delbykeys() - Returns a copy of source string with everything between the first occurance of both key substrings removed
// - only returns first match, and can be used in loops to iterate through large datasets
// - arg 1 is the first key substring to look for
// - arg 2 is the second key substring to look for
// - arg 3 is the source string the search is performed on.
// - arg 4 is boolean and allows you to determine if returned result should include the search keys.
// - arg 5 is boolean and can be used to determine whether search should be case-sensative or not.
//
function substr_delbykeys($key1, $key2, $source, $returnkeys, $casematters) {
if ($casematters === true) {
$start = strpos($source, $key1);
$end = strpos($source, $key2);
} else {
$start = stripos($source, $key1);
$end = stripos($source, $key2);
}
if ($start === false || $end === false) { return false; }
if ($start > $end) {
$temp = $start;
$start = $end;
$end = $temp;
}
if ( $returnkeys === true) {
$start = $start + strlen($key1);
$length = $end - $start;
} else {
$length = ($end + strlen($key2)) - $start;
}
return substr_replace($source, '', $start, $length);
}
?>
With some error catching. Specifically, most of the functions presented require $end to exist, when in fact in my case I needed it to be optional. Use this is $end is optional, and evaluate for FALSE if $start doesn't exist at all:
function get_string_between( $string, $start, $end ){
$string = " " . $string;
$start_ini = strpos( $string, $start );
$end = strpos( $string, $end, $start+1 );
if ($start && $end) {
return substr( $string, $start_ini + strlen($start), strlen( $string )-( $start_ini + $end ) );
} elseif ( $start && !$end ) {
return substr( $string, $start_ini + strlen($start) );
} else {
return FALSE;
}
}
UTF-8 version of #Alejandro Iglesias answer, will work for non-latin characters:
function get_string_between($string, $start, $end){
$string = ' ' . $string;
$ini = mb_strpos($string, $start, 0, 'UTF-8');
if ($ini == 0) return '';
$ini += mb_strlen($start, 'UTF-8');
$len = mb_strpos($string, $end, $ini, 'UTF-8') - $ini;
return mb_substr($string, $ini, $len, 'UTF-8');
}
$fullstring = 'this is my [tag]dog[/tag]';
$parsed = get_string_between($fullstring, '[tag]', '[/tag]');
echo $parsed; // (result = dog)
I use
if (count(explode("<TAG>", $input))>1){
$content = explode("</TAG>",explode("<TAG>", $input)[1])[0];
}else{
$content = "";
}
Subtitue <TAG> for whatever delimiter you want.
I'm searching one PHP function or other solution for my problem.
So, I have a string, this:
$string = 'dfdfdjdkfjsdklfjdksfjekrjekjfdlkfjsdlfdflokuki48(malac)kjdkfdjfkjkejrkerjer';
I'm searching one function, that it has the next parameters:
functionName ($string, $fromCharacters, $toCharacters);
And I run this function:
functionName ($string, 'lokuki48(', ')');
And I will get this: 'malac', or max. this: 'lokuki48(malac)'.
Do you know about PHP function or solution for my problem?
I hope you understand my problem.
Thank you!
try this,
$string = 'dfdfdjdkfjsdklfjdksfjekrjekjfdlkfjsdlfdflokuki48(malac)kjdkfdjfkjkejrkerjer';
if (strpos($string, 'malac') !== false)
{
echo 'true';
}
else
{
echo 'false';
}
https://3v4l.org/SiPvO
i hope it will be helpful.
The strstr() function searches for the first occurrence of a string inside another string.
Example
Find the first occurrence of "world" inside "Hello world!" and return the rest of the string:
<?php
echo strstr("Hello world!","world");
?>
Thanks Guys!
I have found the solution:
`$string = 'dfdfdjdkfjsdklfjdksfjekrjekjfdlkfjsdlfdflokuki48(fasza)kjdkfdjfkjkejrkerjer';
function get_string_between($string, $start, $end){
$string = " ".$string;
$ini = strpos($string,$start);
if ($ini == 0) return "";
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
return substr($string,$ini,$len);
}
echo get_string_between($string,"lokuki48(",")");`
If you love lókuki, use preg_match:
<?php
function search($string, $start, $end)
{
preg_match("'".$start."(.*)".$end."'sim", $string, $out);
if(isset($out[1])) {
return $out[1];
}
return false;
}
$string = 'dfdfdjdkfjsdklfjdksfjekrjekjfdlkfjsdlfdflokuki48(malac)jdkfdjfkjkejrkerjer';
$start="lokuki48\(";
$end="\)";
$res = search($string, $start, $end);
echo $res."\n\n";
$string = 'dfdfdjdkfjsdklfjdksfjekrjekjfdlkfjsdlfdftestfunction(param1, param2)jdkfdjfkjkejrkerjer';
$start="testfunction\(";
$end="\)";
$res = search($string, $start, $end);
echo $res;
Is there a PHP function that can extract a phrase between 2 different characters in a string? Something like substr();
Example:
$String = "[modid=256]";
$First = "=";
$Second = "]";
$id = substr($string, $First, $Second);
Thus $id would be 256
Any help would be appreciated :)
use this code
$input = "[modid=256]";
preg_match('~=(.*?)]~', $input, $output);
echo $output[1]; // 256
working example http://codepad.viper-7.com/0eD2ns
Use:
<?php
$str = "[modid=256]";
$from = "=";
$to = "]";
echo getStringBetween($str,$from,$to);
function getStringBetween($str,$from,$to)
{
$sub = substr($str, strpos($str,$from)+strlen($from),strlen($str));
return substr($sub,0,strpos($sub,$to));
}
?>
$String = "[modid=256]";
$First = "=";
$Second = "]";
$Firstpos=strpos($String, $First);
$Secondpos=strpos($String, $Second);
$id = substr($String , $Firstpos, $Secondpos);
If you don't want to use reqular expresion, use strstr, trim and strrev functions:
// Require PHP 5.3 and higher
$id = trim(strstr(strstr($String, '='), ']', true), '=]');
// Any PHP version
$id = trim(strrev(strstr(strrev((strstr($String, '='))), ']')), '=]');
Regular Expression is your friend.
preg_match("/=(\d+)\]/", $String, $matches);
var_dump($matches);
This will match any number, for other values you will have to adapt it.
You can use a regular expression:
<?php
$string = "[modid=256][modid=345]";
preg_match_all("/\[modid=([0-9]+)\]/", $string, $matches);
$modids = $matches[1];
foreach( $modids as $modid )
echo "$modid\n";
http://eval.in/9913
$str = "[modid=256]";
preg_match('/\[modid=(?P<modId>\d+)\]/', $str, $matches);
echo $matches['modId'];
I think this is the way to get your string:
<?php
function get_string_between($string, $start, $end){
$string = ' ' . $string;
$ini = strpos($string, $start);
if ($ini == 0) return '';
$ini += strlen($start);
$len = strpos($string, $end, $ini) - $ini;
return substr($string, $ini, $len);
}
$fullstring = '.layout {
color: {{ base_color }}
}
li {
color: {{ sub_color }}
}
.text {
color: {{ txt_color }}
}
.btn {
color: {{ btn_color }}
}
.more_text{
color:{{more_color}}
}';
$parsed = get_string_between($fullstring, '{{', '}}');
echo $parsed;
?>
(moved from comment because formating is easier here)
might be a lazy approach, but in such cases i usually would first explode my string like this:
$string_array = explode("=",$String);
and in a second step i would get rid of that "]" maybe through rtrim:
$id = rtrim($string_array[1], "]");
...but this will only work if the structure is always exactly the same...
-cheers-
ps: shouldn't it actually be $String = "[modid=256]"; ?
Try Regular Expression
$String =" [modid=256]";
$result=preg_match_all('/(?<=(=))(\d+)/',$String,$matches);
print_r($matches[0]);
Output
Array ( [0] => 256 )
DEMO
Explanation
Here its used the Positive Look behind (?<=)in regular expression
eg (?<=foo)bar matches bar when preceded by foo,
here (?<=(=))(\d+) we match the (\d+) just after the '=' sign.
\d Matches any digit character (0-9).
+ Matches 1 or more of the preceeding token
You can use a regular expression or you can try this:
$String = "[modid=256]";
$First = "=";
$Second = "]";
$posFirst = strpos($String, $First); //Only return first match
$posSecond = strpos($String, $Second); //Only return first match
if($posFirst !== false && $posSecond !== false && $posFirst < $posSecond){
$id = substr($string, $First, $Second);
}else{
//Not match $First or $Second
}
You should read about substr. The best way for this is a regular expression.
I am searching for a function in PHP to return the array of position of a character in a string.
Inputing those parameters "hello world", 'o' would return (4,7).
Thanks in advance.
No looping needed
$str = 'Hello World';
$letter='o';
$letterPositions = array_keys(array_intersect(str_split($str),array($letter)));
var_dump($letterPositions);
you can check this http://www.php.net/manual/en/function.strpos.php#92849 or http://www.php.net/manual/en/function.strpos.php#87061, there are custom strpos functions to find all occurrences
In PHP no such function exists (AFAIK) that does what you're looking for, but you can make use of preg_match_all to get offsets of a substring pattern:
$str = "hello world";
$r = preg_match_all('/o/', $str, $matches, PREG_OFFSET_CAPTURE);
foreach($matches[0] as &$match) $match = $match[1];
list($matches) = $matches;
unset($match);
var_dump($matches);
Output:
array(2) {
[0]=>
int(4)
[1]=>
int(7)
}
Demo
function searchPositions($text, $needle = ''){
$positions = array();
for($i = 0; $i < strlen($text);$i++){
if($text[$i] == $needle){
$positions[] = $i;
}
}
return $positions;
}
print_r(searchPositions('Hello world!', 'o'));
will do.