I'm sorry, I just found a new problem due to my question about:
Get The Number of Sepecific String Inside String.
I have been trying hard, how to find the number of specific character inside a string? The case something like this.
function get_num_chars($char) {
$string = '120201M, 121212M-1, 21121212M, 232323M-2, 32323K, 323232K-1'
}
If I pass get_num_chars(M) would return 2
If I pass get_num_chars(M-1) would return 1
I tried count_chars(), substr_count() but it doesn't work.
It is possible with substr_count().
I think you are not passing a value to it properly. Try it like this:
$string = '120201M, 121212M-1, 21121212M, 232323M-2, 32323K, 323232K-1';
echo substr_count($string, 'K-1'); //echo's 1
echo substr_count($string, 'K'); // echo's 2
A possible solution using regular expression:
function get_num_chars($char) {
$string = '120201M, 121212M-1, 21121212M, 232323M-2, 32323K, 323232K-1';
return preg_match_all('/'.$char.'(?=,|$)/', $string, $m);
}
echo get_num_chars('M'); // 2
echo get_num_chars('M-1'); // 1
echo get_num_chars('M-2'); // 1
echo get_num_chars('K'); // 1
echo get_num_chars('K-1'); // 1
$k_count = substr_count($string, 'K') - substr_count($string, 'K-');
$k1_count = substr_count($string, 'K-1');
or
Counting K not followed by dash as follows:
$k_count = preg_match_all('/*K(?!-)/*', $string, $out);
Try this. It might not be feasible, but it addresses your problem.
function get_num_chars($char) {
$string = '120201M, 121212M-1, 21121212M, 232323M-2, 32323K, 323232K-1';
echo substr_count($string, $char);
}
get_num_chars('M,');
get_num_chars('M-1');
get_num_chars('k,');
Try this:
$string = '120201M, 121212M-1, 21121212M, 232323M-2, 32323K, 323232K-1';
$wordCounts = array_count_values(str_word_count($string,1));
echo $mCount = (isset($wordCounts['M-'])) ? $wordCounts['M'] : 0;
But here is one thing. You can just pass the 'M-' or 'M', not 'M-1'. It is some workaround for what you want. Because str_word_count matches the exact word count being used.
Related
In trying to figure out how to do it with preg_match, but I'm left with no clue.
So what I'm trying is
$string = 'abc.hello.world.123.hola';
if ($string have 3 or more ".") {
echo 'true';
}
I know you said preg_match, but there is a specific PHP function for this. Use substr_count() :)
$string = 'abc.hello.world.123.hola';
$dots = substr_count($string, '.');
echo $dots; // output: 4
if ($dots >= 3) {
// do something
}
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
I need to find out if there are any redundant words in string or not .Is there any function that can provide me result in true/false.
Example:
$str = "Hey! How are you";
$result = redundant($str);
echo $result ; //result should be 0 or false
But for :
$str = "Hey! How are are you";
$result = redundant($str);
echo $result ; //result should be 1 or true
Thank you
You could use explode to generate an array containing all words in your string:
$array = explode(" ", $str);
Than you could prove if the arrays contains duplicates with the function provided in this answer:
https://stackoverflow.com/a/3145660/5420511
I think this is what you are trying to do, this splits on punctuation marks or whitespaces. The commented out lines can be used if you want the duplicated words:
$str = "Hey! How are are you?";
$output = redundant($str);
echo $output;
function redundant($string){
$words = preg_split('/[[:punct:]\s]+/', $string);
if(max(array_count_values($words)) > 1) {
return 1;
} else {
return 0;
}
//foreach(array_count_values($words) as $word => $count) {
// if($count > 1) {
// echo '"' . $word . '" is in the string more than once';
// }
//}
}
References:
http://php.net/manual/en/function.array-count-values.php
http://php.net/manual/en/function.max.php
http://php.net/manual/en/function.preg-split.php
Regex Demo: https://regex101.com/r/iH0eA6/1
I want to extract the numbers from some strings and enclose them into ... It's something like this:
$string1 = "Up to 3 bedrooms";
$string2 = "With 2 and 3 (wathever)";
echo myMagicFunction($string1); // Up to <span>3</span> bedrooms.
echo myMagicFunction($string2); // With <span>2</span> and <span>3</span> (wathever).
I think I could use preg_replace, but i dont know how...
Tks...
function myMagicFunction($str)
{
return preg_replace('/\d+/', '<span>$0</span>', $str);
}
\d+ to match successive digits, $0 to put match in the replacement string
function myMagicFunction($string) {
return preg_replace('/\d+/', '<span>$0</span>', $string);
}
EDIT: Exactly the same function got posted 1 minute before. I guess there is a definite answer here.
Try this...
$tok = strtok($string1, ' ');
$result = "";
while ($tok !== false) {
if ( is_numeric($tok) )
$result .= "<span>" . $tok . "</span>";
else
$result .= $tok;
$tok = strtok(" \n\t");
}
i have one string
$str ='california 94063';
now i want california and 94063 both in diferent variable.
string can be anything
Thanks in advance....
How about
$strings = explode(' ', $str);
Assuming that your string has ' ' as a separator.
Then, if you want to find the numeric entries of the $strings array, you can use is_numeric function.
Do like this
list($str1,$str2)=explode(' ',$str);
echo $str2;
If your string layout is always the same (say: follows a given format) then I'd use sscanf (http://www.php.net/manual/en/function.sscanf.php).
list($str, $number) = sscanf('california 94063, "%str %d");
<?php
$str ='california 94063';
$x = preg_match('(([a-zA-Z]*) ([0-9]*))',$str, $r);
echo 'String Part='. $r[1];
echo "<br />";
echo 'Number Part='.$r[2];
?>
If text pattern can be changed then I found this solution
Source ::
How to separate letters and digits from a string in php
<?php
$string="94063 california";
$chars = '';
$nums = '';
for ($index=0;$index<strlen($string);$index++) {
if(isNumber($string[$index]))
$nums .= $string[$index];
else
$chars .= $string[$index];
}
echo "Chars: -".trim($chars)."-<br>Nums: -".trim($nums)."-";
function isNumber($c) {
return preg_match('/[0-9]/', $c);
}
?>