Loading... ## 如何在 PHP 中检查字符串是否包含特定单词 ### Answer: Use the PHP strpos() Function You can use the PHP strpos() function to check whether a string contains a specific word or not. The strpos() function returns the position of the first occurrence of a substring in a string. If the substring is not found it returns false. Also note that string positions start at 0, and not 1. Let’s check out an example to understand how this function basically works: ```php <?php $word = "fox"; $mystring = "The quick brown fox jumps over the lazy dog"; // Test if string contains the word if(strpos($mystring, $word) !== false){ echo "Word Found!"; } else{ echo "Word Not Found!"; } ?> ``` ## 如何在 PHP 中获取当前日期和时间 ### Answer: Use the PHP date() Function You can simply use the PHP date() function to get the current data and time in various format, for example, date("d-m-y hs"), date("d/m/y Hs"), and so on. Try out the following example to see how it basically works: ```php <?php // Return current date from the remote server $date = date('d-m-y h:i:s'); echo $date; ?> ``` The date and time returned by the above example is based on the server’s default timezone setting. If you want to show date and time as per user’s timezone, you can set the timezone manually using the date\_default\_timezone\_set() function before the date() function call. The following example shows the date and time in India timezone which is Asia/Kolkata. ```php <?php // Set the new timezone date_default_timezone_set('Asia/Kolkata'); $date = date('d-m-y h:i:s'); echo $date; ?> ``` To learn more about date and time handling, please check out the [PHP date and time tutorial](http://www.bixiaguangnian.com/manual/php7/3981.html "PHP date and time tutorial"). For a complete list of timezones supported by PHP, see [timezone reference](http://www.bixiaguangnian.com/manual/phpfunction/2148.html "timezone reference"). ## 如何在 PHP 中进行重定向 ### Answer: Use the PHP header() Function You can simply use the PHP header() function to redirect a user to a different page. The PHP code in the following example will redirect the user from the page in which it is placed to the URL http://www.example.com/another-page.php. You can also specify relative URLs. ```php <?php header("Location: http://www.example.com/another-page.php"); exit(); ?> ``` If you want to redirect the users from old page to a new page on a permanent basis then also mention HTTP response code in the header() function as shown in the following example, so that search engines transfer “page rank” from the old page to the new page. ```php <?php // 301 Moved Permanently header("Location: http://www.example.com/another-page.php", true, 301); exit(); ?> ``` If the status code is not specified explicitly, for instance header("Location: URL") defaults to 302 (Found). For temporary redirect use the HTTP status code 307. ## 如何在 PHP 中删除字符串中的所有空格 ### Answer: Use the PHP str\_replace() Function You can simply use the PHP str\_replace() function to strip or remove all spaces inside a string. Let’s take a look at the following example to see how it actually works: ```php <?php $str = 'This is a simple piece of text.'; $new_str = str_replace(' ', '', $str); echo $new_str; // Outputs: Thisisasimplepieceoftext. ?> ``` The above example will however only remove spaces. If you want to remove all whitespaces including tabs, newlines, etc. you can use the preg\_replace() function which perform a regular expression search and replace, as demonstrated in the following example: ```php <?php $str = "This is a simple \npiece\tof text."; $new_str = preg_replace("/\s+/", "", $str); echo $new_str; // Outputs: Thisisasimplepieceoftext. ?> ``` In the above example \\t represents the tab character, whereas \\n represents the newline character. To learn more about regular expression, see the tutorial on [PHP regular expressions](http://www.bixiaguangnian.com/manual/php7/3997.html "PHP regular expressions"). ## 如何用 PHP 获取当前年份 ### Answer: Use the PHP date() Function You can simply use the PHP date() function to get the current year. The following example code will be very useful if you want to put a copyright notice in a website footer without worrying about changing it every year. ```php <p>Copyright © <?php echo date("Y"); ?> MyWebsite. All Rights Reserved.</p> ``` ## 如何在 PHP 中将日期从 yyyy-mm-dd 转换为 dd-mm-yyyy 格式 ### Answer: Use the strtotime() Function You can first use the PHP strtotime() function to convert any textual datetime into Unix timestamp, then simply use the PHP date() function to convert this timestamp into desired date format. The following example will convert a date from yyyy-mm-dd format to dd-mm-yyyy. ```php <?php $original_date = "2019-03-31"; // Creating timestamp from given date $timestamp = strtotime($original_date); // Creating new date format from that timestamp $new_date = date("d-m-Y", $timestamp); echo $new_date; // Outputs: 31-03-2019 ?> ``` ## 如何在 PHP 中将字符串转换为数字 ### Answer: Use Type Casting As we know PHP does not require or support explicit type definition in variable declaration. However, you can force a variable to be evaluated as a certain type using type casting. Let’s try out the following example to understand how this works: ```php <?php $num = "2.75"; // Cast to integer $int = (int)$num; echo gettype($int); // Outputs: integer echo $int; // Outputs: 2 // Cast to float $float = (float)$num; echo gettype($float); // Outputs: double echo $float; // Outputs: 2.75 ?> ``` You can use (int) or (integer) to cast a variable to integer, use (float), (double) or (real) to cast a variable to float. Similarly, you can use the (string) to cast a variable to string, and so on. The PHP gettype() function returns “double” in case of a float for historical reasons. Alternatively, you can also use the intval() function to get the integer value of a variable. ```php <?php echo intval(2); // Outputs: 2 echo intval(2.75); // Outputs: 2 echo intval('34'); // Outputs: 34 echo intval('+34'); // Outputs: 34 echo intval('-34'); // Outputs: -34 echo intval(034); // Outputs: 28 echo intval('034'); // Outputs: 34 echo intval(1e10); // Outputs: 10000000000 echo intval('1e10'); // Outputs: 10000000000 echo intval(0xff); // Outputs: 255 echo intval('0xff'); // Outputs: 0 ?> ``` ## 如何在 PHP 中获取数组的第一个元素 ### Answer: Use the PHP array\_values() Function If you know the exact index or key of an array you can easily get the first element, like this: ```php <?php // A sample indexed array $cities = array("London", "Paris", "New York"); echo $cities[0]; // Outputs: London // A sample associative array $fruits = array("a" => "Apple", "b" => "Ball", "c" => "Cat"); echo $fruits["a"]; // Outputs: Apple ?> ``` However, there are certain situations where you don’t know the exact index or key of the first element. In that case you can use the array\_values() function which returns all the values from the array and indexes the array numerically, as shown in the following example: ```php <?php $arr = array(3 => "Apple", 5 => "Ball", 11 => "Cat"); echo array_values($arr)[0]; // Outputs: Apple ?> ``` Alternativly, you can also use the reset() function to get the first element. The reset() function set the internal pointer of an array to its first element and returns the value of the first array element, or FALSE if the array is empty. You can also use the current() function to get the first element of an array. This function returns the current element in an array, which is the first element by default unless you’ve re-positioned the array pointer, otherwise use the reset() function. Here’s an example: ```php <?php $arr = array(3 => "Apple", 5 => "Ball", 11 => "Cat"); echo current($arr); // Outputs: Apple echo reset($arr); // Outputs: Apple echo next($arr); // Outputs: Ball echo current($arr); // Outputs: Ball echo reset($arr); // Outputs: Apple ?> ``` ## 如何在 PHP 中将日期转换为时间戳 ### Answer: Use the strtotime() Function You can use the PHP strtotime() function to convert any textual datetime into Unix timestamp. The following example demonstrates how this function actually works: ```php <?php $date1 = "2019-05-16"; $timestamp1 = strtotime($date1); echo $timestamp1; // Outputs: 1557964800 $date2 = "16-05-2019"; $timestamp2 = strtotime($date2); echo $timestamp2; // Outputs: 1557964800 $date3 = "16 May 2019"; $timestamp3 = strtotime($date3); echo $timestamp3; // Outputs: 1557964800 ?> ``` As you can see in the above example the resulting timestamp is equivalent for the same date with different format. You can also use other variations of English date format. ## 如何在 PHP 中为空数组添加元素 ### Answer: Use the array\_push() Function You can simply use the array\_push() function to add new elements or values to an empty PHP array. Let’s take a look at an example to understand how it basically works: ```php <?php // Adding values one by one $array1 = array(); array_push($array1, 1); array_push($array1, 2); array_push($array1, 3); print_r($array1); echo "<br>"; // Adding all values at once $array2 = array(); array_push($array2, 1, 2, 3); print_r($array2); echo "<br>"; // Adding values through loop $array3 = array(); for($i=1; $i<=3; $i++){ $array3[] = $i; } print_r($array3); ?> ``` ## 如何在 PHP 中把整数转换成字符串 ### Answer: Use the strval() Function You can simply use type casting or the strval() function to convert an integer to a string in PHP. Let’s take a look at an example to understand how it basically works: ```php <?php // Sample integer $int = 10; // Casting integer to string $var1 = (string) $int; // $var1 is a string var_dump($var1); // Getting string value of a variable $var2 = strval($int); // $var2 is a string var_dump($var2); ?> ``` ## 如何用值而不是键删除 PHP 数组元素 ### Answer: Use the array\_search() Function You can use the array\_search() function to first search the given value inside the array and get its corresponding key, and later remove the element using that key with unset() function. Please note that, if the value is found more than once, only the first matching key is returned. Let’s take a look at an example to understand how it actually works: ```php <?php // Sample indexed array $array1 = array(1, 2, 3, 4, 5); // Search value and delete if(($key = array_search(4, $array1)) !== false) { unset($array1[$key]); } print_r($array1); echo "<br>"; // Sample eassociative array $array2 = array("a" => "Apple", "b" => "Ball", "c" => "Cat"); // Search value and delete if(($key = array_search("Cat", $array2)) !== false) { unset($array2[$key]); } print_r($array2); ?> ``` ## 如何在 PHP 中将键和值同时推入数组 ### Answer: Use the Square Bracket [] Syntax You can simply use the square bracket [] notation to add or push a key and value pair into a PHP associative array. Let’s take a look at an example to understand how it basically works: ```php <?php // Sample array $array = array("a" => "Apple", "b" => "Ball", "c" => "Cat"); // Adding key-value pairs to an array $array["d"] = "Dog"; $array["e"] = "Elephant"; print_r($array); ?> ``` ## 如何使用 PHP 定期刷新页面 ### Answer: Use the header() Function You can simply use the header() function to automatically refresh a page periodically (i.e. at certain time intervals) using PHP. Please, note that header() function must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP script. The following example will refreshes the current page every five seconds. ```php <?php header("refresh: 5;"); ?> ``` ## 如何从 PHP 字符串中删除最后一个字符 ### Answer: Use the rtrim() Function You can simply use the rtrim() function to remove the last character from a string. Let’s take a look at an example to understand how it actually works: ```php <?php // Sample string $str1 = "Hello World!"; echo rtrim($str1, "!"); // Outputs: Hello World echo "<br>"; // Sample string $str2 = "red, green, blue, "; echo rtrim($str2, ", "); // Outputs: red, green, blue ?> ``` ## 如何从 PHP 脚本返回 JSON ### Answer: Use the json\_encode() Function You can simply use the json\_encode() function to return JSON response from a PHP script. Also, if you’re passing JSON data to a JavaScript program, make sure set the Content-Type header. Let’s take a look at an example to understand how it basically works: ```php <?php // Sample array $data = array("a" => "Apple", "b" => "Ball", "c" => "Cat"); header("Content-Type: application/json"); echo json_encode($data); exit(); ?> ``` ## 如何让 PHP 显示错误 ### Answer: Use the ini\_set() Function For security reasons, error display in production environments is disabled by default. But, if you want to display errors in a PHP file for debugging purposes, you can place these lines of code at the top of your PHP file, as shown in the following example: ```php <?php ini_set('display_errors', 1); ini_set('display_startup_errors', 1); ini_set('error_reporting', -1); // Rest of code here... ?> ``` However, this doesn't make PHP to show parse errors (such as missing semicolon). The only way to show those errors is to set the display\_errors directive to On in php.ini file. By default display\_errors set to Off for production environments. ```php display_errors = On ``` After modifying the php.ini file restart your web server, or php-fpm service if you are using PHP-FPM. However, if you don’t have access to php.ini file—for instance, if you’re using a shared hosting—then putting the following line in .htaccess file might also work. ```php php_flag display_errors 1 ``` > Warning: Outputting errors in production environments could be very dangerous. Sensitive information could potentially leak out of your application such as database usernames and passwords or worse. For production environments, logging errors is recommended. Last modification:September 19, 2024 © Allow specification reprint Like 1 如果觉得我的文章对你有用,请随意赞赏