delete all chars when '-' found php - php

Having strings like
$s1 = "Elegan-71";
$s2 = "DganSD-171";
$s2 = "SD-1";
what would be the best way to delete all chars from '-' to end like
$cleans1 = "Elegan";
$cleans2 = "DganSD";
$cleans2 = "SD";
There is substr($s1, "-",4);
substr(string $string, int $start, int[optional] $length=null);
but how to tell that it should remove all numbers and how to know numbers size as they are variable?

list($cleans1) = explode("-",$s1,2);

This will do what you want:
<?php
$my_string = "happy-123";
$hyphen_position = strrpos($my_string, '-');
$fixed_string = substr($my_string, 0, $hyphen_position);
echo $fixed_string;
?>

$s1 = "Elegan-71";
if (strrpos($s1, '-')){
$cleans1 = substr($s1, 0, strrpos($s1, '-'));
}else{
$cleans1 = $s1;
}
That should do the trick.

Assuming you are cleaning each string individually, and you don't want to end up with neither an array or a list, and that each string ends up in that pattern (dash and number), this should do the trick:
$cleans1 = preg_replace('/-\d+$/', '', $s1);

ststr can does it too.
$s1 = "Elegan-71";
$clean = strstr($s1, '-', true);
echo $clean;

i like :
$cleans1 = strtok($s1, "-");
about strtok

Related

how i can display only 2 phrase from sql [duplicate]

Is there a way to trim a text string in PHP so it has a certain number of characters? For instance, if I had the string:
$string = "this is a string";
How could I trim it to say:
$newstring = "this is";
This is what I have so far, using chunk_split(), but it isn't working. Can anyone improve on my method?
function trimtext($text)
{
$newtext = chunk_split($text,15);
return $newtext;
}
I also looked at this question, but I don't really understand it.
if (strlen($yourString) > 15) // if you want...
{
$maxLength = 14;
$yourString = substr($yourString, 0, $maxLength);
}
will do the job.
Take a look here.
substr cuts words in half. Also if word contains UTF8 characters, it misbehaves. So it would be better to use mb_substr:
$string = mb_substr('word word word word', 0, 10, 'utf8').'...';
You didn't say the reason for this but think about what you want to achieve. Here is a function for shorten a string word by word with or without adding ellipses at the end:
function limitStrlen($input, $length, $ellipses = true, $strip_html = true) {
//strip tags, if desired
if ($strip_html) {
$input = strip_tags($input);
}
//no need to trim, already shorter than trim length
if (strlen($input) <= $length) {
return $input;
}
//find last space within length
$last_space = strrpos(substr($input, 0, $length), ' ');
if($last_space !== false) {
$trimmed_text = substr($input, 0, $last_space);
} else {
$trimmed_text = substr($input, 0, $length);
}
//add ellipses (...)
if ($ellipses) {
$trimmed_text .= '...';
}
return $trimmed_text;
}
function trimtext($text, $start, $len)
{
return substr($text, $start, $len);
}
You can call the function like this:
$string = trimtext("this is a string", 0, 10);
Would return:
This is a
substr let's you take a portion of string consisting of exactly as much characters as you need.
You can use this
substr()
function to get substring
If you want to get a string with a certain number of characters you can use substr, i.e.
$newtext = substr($string,0,$length);
where $length is the given length of the new string.
If you want an abstract for the first 10 words (you can use html in $text, before script there is strip_tags)
use this code:
preg_match('/^([^.!?\s]*[\.!?\s]+){0,10}/', strip_tags($text), $abstract);
echo $abstract[0];
My function has some length to it, but I like to use it. I convert the string int to a Array.
function truncate($text, $limit){
//Set Up
$array = [];
$count = -1;
//Turning String into an Array
$split_text = explode(" ", $text);
//Loop for the length of words you want
while($count < $limit - 1){
$count++;
$array[] = $split_text[$count];
}
//Converting Array back into a String
$text = implode(" ", $array);
return $text." ...";
}
Or if the text is coming from an editor and you want to strip out the HTML tags.
function truncate($text, $limit){
//Set Up
$array = [];
$count = -1;
$text = filter_var($text, FILTER_SANITIZE_STRING);
//Turning String into an Array
$split_text = preg_split('/\s+/', $text);
//Loop for the length of words you want
while($count < $limit){
$count++;
$array[] = $split_text[$count];
}
//Converting Array back into a String
$text = implode(" ", $array);
return $text." ...";
}
With elipsis (...) only if longer - and taking care of special language-specific characters:
mb_strlen($text,'UTF-8') > 60 ? mb_substr($text, 0, 60,'UTF-8') . "…" : $text;

Separation of string into multiple string value

I have a string with underscores(_). What I want is to get the string value after the first underscore and considered as the first string value and the second string value will be the whole string after the underscore of the first string value using php.
Example:
$string = "Makes_me_wonder";
Result I want:
$str1 = "me";
$str2 = "wonder";
Another variable I am having:
$string = "I_wont_gohome_withoutyou";
Result should be:
$str1 = "wont";
$str2 = "gohome_withoutyou";
Another one:
$string = 'Never_gonna_leave_this_bed";
Output i want:-
$str1 = "gonna_leave";
$str2 = "this_bed";
Please help me. Thanks.
You can use explode with 3rd parameter - limit:
DEMO
$string = "I_wont_gohome_withoutyou";
$arr = explode("_",$string,3);
$str1 = $arr[1]; //wont
$str2 = $arr[2]; //gohome_withoutyou
Provided that you have two or more _ in a word strictly. If it is so, there needs a work around too.
function explode($string)
{
$delimiter = '_';
return explode($delimiter, explode($delimiter, $string, 2)[1], 2);
}
$string = "Makes_me_wonder";
$strings = explode($string);
echo $strings[0]; //me
echo $strings[1]; //wonder
$string = "I_wont_gohome_withoutyou";
$strings = explode($string);
echo $strings[0]; //wont
echo $strings[1]; //gohome_withoutyou
I think your solution is like this:-
<?php
function getfinal_result($string){
$final_data = explode('_',$string,2)[1]; // explode with first occurrence of _ and leave first word
if(substr_count($final_data,'_')>2){ // now check _ remains is greater that 2
$first_data = substr($final_data , 0, strpos($final_data , '_', strpos($final_data , '_')+1)); // find the string comes after second _
$second_data = str_replace($first_data.'_','',$final_data); // get the string before the second _
$last_data = Array($first_data,$second_data); // assign them to final data
}else{
$last_data = explode('_',$final_data,2); // directly explode with first occurance of _
}
return $last_data; // return final data
}
$first_data = getfinal_result('Makes_me_wonder');
$second_data = getfinal_result('I_wont_gohome_withoutyou');
$third_data = getfinal_result('Never_gonna_leave_this_bed');
echo "<pre/>";print_r($first_data);
echo "<pre/>";print_r($second_data);
echo "<pre/>";print_r($third_data);
?>
Output:- https://eval.in/593240
There are multiple methods but here's one of them.
$pos1 = strpos($string, '_');
$pos2 = strpos($string, '_', $pos1 + 1);
$str1 = substr($string, $pos1 + 1, $pos2 - $pos1 - 1);
$str2 = substr($string, $pos2 + 1);
This assumes that there are at least 2 underscores in the string.

Remove decimal point e.g. 99.99 = 9999

I am trying to find a way to remove a decimal point from a number.
E.g.
1.11 would equal 111
9.99 would equal 999
1.1111 would equal 11111
Can't seem to find the function I need to do this. I have been googling to find this function but no luck.
I have tried these functions but it is not what I am looking for:
floor(99.99) = 99
round(99.99) = 100
number_format(99.99) = 100
This should work for you:
<?php
$str = "9.99";
echo $str = str_replace(".", "", $str);
?>
Output:
999
We can use explode:
$num = 99.999;
$final = '';
$segments = explode($num, '.');
foreach ($segments as $segment){
$final .= $segment;
}
echo $final;
Checkout this demo: http://codepad.org/DMiFNYfB
Generalizing the solution for any local settings variations we can use preg_split as follows:
$num = 99.999;
$final = '';
$pat = "/[^a-zA-Z0-9]/";
$segments = preg_split($pat, $num);
foreach ($segments as $segment){
$final .= $segment;
}
echo $final;
Also, there are another solution using for loop:
<?php
$num = 99.999;
$num = "$num"; //casting number to be string
$final = '';
for ($i =0; $i < strlen($num); $i++){
if ($num[$i] == '.') continue;
$final .= $num[$i];
}
echo $final;
If you want to simply remove the decimal, you can just replace it.
str_replace('.', '', $string);
You could just treat it as a string and remove the . character:
$num = str_replace ('.', '', $num);
Try:
$num = 1.11; // number 1.11
$num_to_str = strval($num); // convert number to string "1.11"
$no_decimals = str_replace(".", "", $num_to_str); // remove decimal point "111"
$str_to_num = intval($no_decimals); // convert back to number 111
All in one line would be something like:
$num_without_decimals = intval(str_replace(".", "", strval(1.11)));

Shorten a text string in PHP

Is there a way to trim a text string in PHP so it has a certain number of characters? For instance, if I had the string:
$string = "this is a string";
How could I trim it to say:
$newstring = "this is";
This is what I have so far, using chunk_split(), but it isn't working. Can anyone improve on my method?
function trimtext($text)
{
$newtext = chunk_split($text,15);
return $newtext;
}
I also looked at this question, but I don't really understand it.
if (strlen($yourString) > 15) // if you want...
{
$maxLength = 14;
$yourString = substr($yourString, 0, $maxLength);
}
will do the job.
Take a look here.
substr cuts words in half. Also if word contains UTF8 characters, it misbehaves. So it would be better to use mb_substr:
$string = mb_substr('word word word word', 0, 10, 'utf8').'...';
You didn't say the reason for this but think about what you want to achieve. Here is a function for shorten a string word by word with or without adding ellipses at the end:
function limitStrlen($input, $length, $ellipses = true, $strip_html = true) {
//strip tags, if desired
if ($strip_html) {
$input = strip_tags($input);
}
//no need to trim, already shorter than trim length
if (strlen($input) <= $length) {
return $input;
}
//find last space within length
$last_space = strrpos(substr($input, 0, $length), ' ');
if($last_space !== false) {
$trimmed_text = substr($input, 0, $last_space);
} else {
$trimmed_text = substr($input, 0, $length);
}
//add ellipses (...)
if ($ellipses) {
$trimmed_text .= '...';
}
return $trimmed_text;
}
function trimtext($text, $start, $len)
{
return substr($text, $start, $len);
}
You can call the function like this:
$string = trimtext("this is a string", 0, 10);
Would return:
This is a
substr let's you take a portion of string consisting of exactly as much characters as you need.
You can use this
substr()
function to get substring
If you want to get a string with a certain number of characters you can use substr, i.e.
$newtext = substr($string,0,$length);
where $length is the given length of the new string.
If you want an abstract for the first 10 words (you can use html in $text, before script there is strip_tags)
use this code:
preg_match('/^([^.!?\s]*[\.!?\s]+){0,10}/', strip_tags($text), $abstract);
echo $abstract[0];
My function has some length to it, but I like to use it. I convert the string int to a Array.
function truncate($text, $limit){
//Set Up
$array = [];
$count = -1;
//Turning String into an Array
$split_text = explode(" ", $text);
//Loop for the length of words you want
while($count < $limit - 1){
$count++;
$array[] = $split_text[$count];
}
//Converting Array back into a String
$text = implode(" ", $array);
return $text." ...";
}
Or if the text is coming from an editor and you want to strip out the HTML tags.
function truncate($text, $limit){
//Set Up
$array = [];
$count = -1;
$text = filter_var($text, FILTER_SANITIZE_STRING);
//Turning String into an Array
$split_text = preg_split('/\s+/', $text);
//Loop for the length of words you want
while($count < $limit){
$count++;
$array[] = $split_text[$count];
}
//Converting Array back into a String
$text = implode(" ", $array);
return $text." ...";
}
With elipsis (...) only if longer - and taking care of special language-specific characters:
mb_strlen($text,'UTF-8') > 60 ? mb_substr($text, 0, 60,'UTF-8') . "…" : $text;

String function php

I get a string like 0699245221 and i want this result 06-99-24-52-21, do you know the best solution for this ? (Forget loop, or other, i'm sure php have got this "function".
Thank's in advance.
$string = '0699245221';
$modified_string = wordwrap($string, 2, '-', true);
http://www.php.net/manual/es/function.wordwrap.php
$str = "0699245221";
$str = wordwrap($str, 2, '-', true);
output: 06-99-24-52-21
Try this :
$str = '0699245221';
echo $res = implode("-",str_split($str, 2));
OR
$str = '0699245221';
echo $res = chunk_split ($str, 2, '-');
Second one has one issue that it adds a - at the end
Try this
<?php
$value = '0699245221';
echo $res = implode("-",str_split($value, 2));
?>
Output
06-99-24-52-21
There are many ways to do this. You could use something like this:
function addDashes($str) {
$str = str_split($str, 2);
$str = implode("-", $str);
return $str;
}
or this:
function addDashes($str) {
$str = chunk_split($string, 2, "-");
$str = substr($str, 0, -1);
return $str;
}
This is perfect solution tried and he give you the result like this 06-99-24-52-21
<?php
$str = "0699245221";
$str1= chunk_split($str,2,"-");
$str1=rtrim($str1,"-");
echo $str1;
?>

Categories