I'm trying to limit my PHP echo to only 200 characters and then if there are any more replace them with "...".
How could I modify the following statement to allow this?
<?php echo $row['style-info'] ?>
Well, you could make a custom function:
function custom_echo($x, $length)
{
if(strlen($x)<=$length)
{
echo $x;
}
else
{
$y=substr($x,0,$length) . '...';
echo $y;
}
}
You use it like this:
<?php custom_echo($row['style-info'], 200); ?>
Not sure why no one mentioned this before -
echo mb_strimwidth("Hello World", 0, 10, "...");
// output: "Hello W..."
More info check - http://php.net/manual/en/function.mb-strimwidth.php
Like this:
echo substr($row['style-info'], 0, 200);
Or wrapped in a function:
function echo_200($str){
echo substr($row['style-info'], 0, 200);
}
echo_200($str);
<?php echo substr($row['style_info'], 0, 200) .((strlen($row['style_info']) > 200) ? '...' : ''); ?>
It gives out a string of max 200 characters OR 200 normal characters OR 200 characters followed by '...'
$ur_str= (strlen($ur_str) > 200) ? substr($ur_str,0,200).'...' :$ur_str;
This one worked for me and it's also very easy
<?php
$position=14; // Define how many character you want to display.
$message="You are now joining over 2000 current";
$post = substr($message, 0, $position);
echo $post;
echo "...";
?>
<?php
if(strlen($var) > 200){
echo substr($var,0,200) . " ...";
}
else{
echo $var;
}
?>
this is most easy way for doing that
//substr(string,start,length)
substr("Hello Word", 0, 5);
substr($text, 0, 5);
substr($row['style-info'], 0, 5);
for more detail
https://www.w3schools.com/php/func_string_substr.asp
http://php.net/manual/en/function.substr.php
string substr ( string $string , int $start [, int $length ] )
http://php.net/manual/en/function.substr.php
more flexible way is a function with two parameters:
function lchar($str,$val){return strlen($str)<=$val?$str:substr($str,0,$val).'...';}
usage:
echo lchar($str,200);
function TitleTextLimit($text,$limit=200){
if(strlen($text)<=$limit){
echo $text;
}else{
$text = substr($text,0,$limit) . '...';
echo $text;
}
echo strlen($row['style-info']) > 200) ? substr($row['style-info'], 0, 200)."..." : $row['style-info'];
echo strlen($row['style-info'])<=200 ? $row['style-info'] : substr($row['style-info'],0,200).'...';
Try This:
echo ((strlen($row['style-info']) > 200) ? substr($row['style-info'],0,200).'...' : $row['style-info']);
In this code we define a method and then we can simply call it. we give it two parameters. first one is text and the second one should be count of characters that you wanna display.
function the_excerpt(string $text,int $length){
if(strlen($text) > $length){$text = substr($text,0,$length);}
return $text;
}
Related
I want to make php fgets(STDIN). But I don't know how to restrict the input count and i don't know how to accept only specific letters. Please guide me. I write down the problems of mine. I'm the beginner in STDIN usage. It's important for me because i have to do it in my Programming Test Exam. Help me please.
Here is Problem 1
Problem 1: I want to get only 10 Letters from cmd input and these
input should be W & S.
Here is Problem 2
Problem 2 : I want to get only 3 numbers and how to restrict the cmd
input to only number.
I just realized Ive misread your question for part 2, but this will work for part one and be a good help to start problem 2:
<?php
$errorMessage = false;
$attempts = 1;
$maxAttempts = 5;
function validates($string)
{
global $errorMessage; //tell this function to use global errormessage
if (strlen($string) > 10) {
$errorMessage = 'Exceeded String Length. Please ensure no more than 10 characters are entered';
return false;
}
preg_match('/\d+/', $string, $matches);
$extractedDigits = (isset($matches[0]) ? $matches[0] : 0 );
if ($extractedDigits > 3) {
$errorMessage = 'Exceeded allowed number of digits. Please ensure no more than 3 digits are contained in the string';
return false;
}
$errorMessage = false;
return true;
}
$result = readline('please enter a valid string: ');
while (!validates($result) && $attempts < $maxAttempts) { //while fail validation and have attempted less than the max attampts
echo "\n";
echo '*******************************************';
echo "\n";
echo 'Attempts Left (' . ($maxAttempts - $attempts) . ')';
echo "\n";
$result = readline($errorMessage . '. Please try again: ');
$attempts++;
}
echo "\n";
echo '*******************************************';
echo "\n";
if ($attempts >= $maxAttempts) {
echo 'Failed, too many attempts';
} else {
echo "\n";
echo 'Success...';
echo "\n";
echo "\n";
echo $result;
echo "\n";
echo "\n";
}
echo "\n";
How to compare 2 variable using php like this ?
$aaa = "1234567890qwertyuiopsdflkjwerouioiuweewjkee";
$bbb = "1234567890qwertyuiop";
How to check
if(first char to twenty char of $aaa == $bbb)
{ echo "same"; }
else
{ echo "not same"; }
I assume you are searching for strncmp:
This function is similar to strcmp(), with the difference that you can specify the (upper limit of the) number of characters from each string to be used in the comparison.
if(strncmp($aaa, $bbb, 20) == 0) {
# First twenty characters match.
} else {
# First twenty characters don't match.
}
$aaafirst20 = $small = substr($aaa, 0, 20);
if(strcmp($aaafirst20 , $bbb){
}
else{
}
Try this :
You can use strcmp function for the same.
PHP docs # strcmp
if(strcmp($aaa,$bbb)){
echo "same";
} else {
echo "not same";
}
You can use strpos() to check if $bbb is found in $aaa, and starts at position 0.
if (strpos($aaa, $bbb) === 0) {
echo 'Same';
}
else echo 'Not same';
See demo
Your exact solution would be
// first reduce a to its first 20 characters
$trimmed = substr($aaa, 0, 20);
// now compare with b
if($trimmed == $bbb){
// same
}
Or, all in one line
if(substr($aaa, 0, 20) == $bbb){
// same
}
Good day.
I have link http://vk.com/id98429809?z=photo98429809_299166823%2Falbum98429809_0%2Frev
Tell me please how get:
$id=$arr['id']; // $id = 98429809
$type=$arr['type']; // $type= photo
$num=$arr['num']; // $num= 299166823
Tell me please how explode link and get this ?
Try this,
<?php
$str='photo98429809_299166823';
$arr=explode('_',$str);
$num=$arr[1]; // $num= 299166823
preg_match('/^[a-z]+/i', $arr[0], $m);
$type=$m[0];
$id=str_replace($type,"",$arr[0]);
$num=$arr[1];
echo '<br/>';
echo $id;
echo '<br/>';
echo $type;
echo '<br/>';
echo $num;
?>
Tested on http://writecodeonline.com/php/
Try it, i think it's easy and useful for u
$str=$_GET["z"];
$arr['type']=substr($str,0,5) ;
$arr['id']=substr($str,5,8) ;
$arr['num']=substr($str,14,3) ;
echo $arr['id']." ".$arr['type']." ".$arr['num'];
$url = "http://vk.com/id98429809?z=photo98429809_299166823%2Falbum98429809_0%2Frev";
if (preg_match('#=([^\d]+)([\d]+)_([\d]+)#', $url, $matches)) {
$id = $matches[2];
$type = $matches[1];
$num = $matches[3];
}
Universal answer for all links vk.com
if(substr_count($link,"photo")>0){
$type='photo'; $arg='photo';
}
elseif(substr_count($link,"video")>0){
$type='video'; $arg='video';
}
elseif(substr_count($link,"id")>0){
$type='id'; $arg='id';
}
else{
$type='id'; $arg='/';
}
$arr1=explode($arg,$link);
if($arg=='photo'){
$arr2=explode($arg,$arr1[1]);
$arr3=explode('_',$arr2[0]);
$id=$arr3[0];
$item_id=substr($arr3[1],0,9);
}
elseif($arg=='video'){
$arr2=explode($arg,$arr1[1]);
$arr3=explode('_',$arr2[0]);
$id=$arr3[0];
$item_id=substr($arr3[1],0,9);
}
elseif($arg=='id' || $arg=='/'){
$id=$arr1[1];
$item_id=$arr1[1];
}
echo $link;
echo '<br>id = '.$id.'<br>item_id = '.$item_id;
Code big, but he work for all links
Thanks all for help!
I'm using this code to set the limit of 300 characters to the_content.
How can i set when i want to use it and when i dont ?
<?php
add_filter("the_content", "plugin_myContentFilter");
function plugin_myContentFilter($content)
{
// Take the existing content and return a subset of it
return substr($content, 0, 300);
}
?>
<?php
function plugin_myContentFilter($content) {
if (!is_single()) {
return substr($content, 0, 300);
} else {
return $content;
}
}
add_filter("the_content", "plugin_myContentFilter");
?>
Will shorten the content to 300 characters unless on a single post page.
I was wondering if there is any way to detect if a number is negative in PHP?
I have the following code:
$profitloss = $result->date_sold_price - $result->date_bought_price;
I need to find out if $profitloss is negative and if it is, I need to echo out that it is.
if ($profitloss < 0)
{
echo "The profitloss is negative";
}
Edit: I feel like this was too simple an answer for the rep so here's something that you may also find helpful.
In PHP we can find the absolute value of an integer by using the abs() function. For example if I were trying to work out the difference between two figures I could do this:
$turnover = 10000;
$overheads = 12500;
$difference = abs($turnover-$overheads);
echo "The Difference is ".$difference;
This would produce The Difference is 2500.
I believe this is what you were looking for:
class Expression {
protected $expression;
protected $result;
public function __construct($expression) {
$this->expression = $expression;
}
public function evaluate() {
$this->result = eval("return ".$this->expression.";");
return $this;
}
public function getResult() {
return $this->result;
}
}
class NegativeFinder {
protected $expressionObj;
public function __construct(Expression $expressionObj) {
$this->expressionObj = $expressionObj;
}
public function isItNegative() {
$result = $this->expressionObj->evaluate()->getResult();
if($this->hasMinusSign($result)) {
return true;
} else {
return false;
}
}
protected function hasMinusSign($value) {
return (substr(strval($value), 0, 1) == "-");
}
}
Usage:
$soldPrice = 1;
$boughtPrice = 2;
$negativeFinderObj = new NegativeFinder(new Expression("$soldPrice - $boughtPrice"));
echo ($negativeFinderObj->isItNegative()) ? "It is negative!" : "It is not negative :(";
Do however note that eval is a dangerous function, therefore use it only if you really, really need to find out if a number is negative.
:-)
if(x < 0)
if(abs(x) != x)
if(substr(strval(x), 0, 1) == "-")
You could check if $profitloss < 0
if ($profitloss < 0):
echo "Less than 0\n";
endif;
if ( $profitloss < 0 ) {
echo "negative";
};
Don't get me wrong, but you can do this way ;)
function nagitive_check($value){
if (isset($value)){
if (substr(strval($value), 0, 1) == "-"){
return 'It is negative<br>';
} else {
return 'It is not negative!<br>';
}
}
}
Output:
echo nagitive_check(-100); // It is negative
echo nagitive_check(200); // It is not negative!
echo nagitive_check(200-300); // It is negative
echo nagitive_check(200-300+1000); // It is not negative!
Just multiply the number by -1 and check if the result is positive.
You could use a ternary operator like this one, to make it a one liner.
echo ($profitloss < 0) ? 'false' : 'true';
I assume that the main idea is to find if number is negative and display it in correct format.
For those who use PHP5.3 might be interested in using Number Formatter Class - http://php.net/manual/en/class.numberformatter.php. This function, as well as range of other useful things, can format your number.
$profitLoss = 25000 - 55000;
$a= new \NumberFormatter("en-UK", \NumberFormatter::CURRENCY);
$a->formatCurrency($profitLoss, 'EUR');
// would display (€30,000.00)
Here also a reference to why brackets are used for negative numbers:
http://www.open.edu/openlearn/money-management/introduction-bookkeeping-and-accounting/content-section-1.7
Can be easily achieved with a ternary operator.
$is_negative = $profitloss < 0 ? true : false;
I wrote a Helper function for my Laravel project but can be used anywhere.
function isNegative($value){
if(isset($value)) {
if ((int)$value > 0) {
return false;
}
return (int)$value < 0 && substr(strval($value), 0, 1) === "-";
}
}