Home > Backend Development > PHP Tutorial > PHP interview questions compiled and shared

PHP interview questions compiled and shared

小云云
Release: 2023-03-22 11:56:01
Original
4414 people have browsed it

This article mainly shares with you the collection and sharing of PHP interview questions, hoping to help you have a smoother interview.

Server aspect

1. nginx smooth restart

nginx runs a new worker process and calmly closes the old worker process, notifies the worker process to close the listening socket, but continues to connect to the current one provide services to customers. After all client services are completed, the old worker process is
closed. If application of the new configuration file fails, nginx will continue to work using the old configuration file.
To put it simply, nginx will continue to process the previous request and start a new process to handle the new request. The old process will be killed after the processing is completed.

2. Get the last 10 lines of the file.
tail -10 a.log

3. Check the processes that occupy more system resources
top
ps: After entering the top command, press 1 to see the memory and cpu usage

3. View keyword occurrence function
grep -n 'I am the keyword you want to find' a.txt | cut -d ":" - f1

Statistics of keywords in the file Which line appears:
grep -n "Keyword" "File path" | cut -d ":" -f1
The last line number where the keyword appears in the statistics file:
grep -n "Keyword" "File path" | tail -n 1 | cut -d ":" -f1


4. Search for files with the keyword "www" in the /root/ directory. Run the command in the terminal:
find /root/ –type f | xargs grep “www

5. Statistics of file lines
wc -l a.txt

Statistics demo The number of js files in the directory:
find demo/ -name "*.js" |wc -l
Count the number of code lines of all js files in the demo directory:
find demo/ -name "*.js" " |xargs cat|wc -l
wc -l `find ./ -name "*.js"`|tail -n1
Count the number of code lines of all js files in the demo directory, and filter out blank lines:
find /demo -name "*.js" |xargs cat|grep -v ^$|wc -l

6. Monitor a file in real time
tail -f a.log

7. The 100 most visited IPs and the number of visits in the nginx log
The 100 most visited IPs and the number of visits in the nginx log
awk '{print $1}' /opt/software/nginx/logs/ access.log| sort | uniq -c | sort -n -k 1 -r | head -n 100

8. In the compiled php, add a new extension
────── ------------------------------------------------
Source code installation
1. Find the source code directory of php
2. Jump to the EXT directory
3. Execute phpize to generate the configure file
4. ./configure --with-php-config=/usr/local/php/bin/php-config
5. Compile make
6. Compile and install make install
7. Modify php.ini extension=/usr/local/***.so
8. Restart php-fpm

YUM installation:
1. Go to PHP’s official website to download the source code (htpp://pecl.php.net)
2. Unzip the file
3. Execute phpize to generate the configure file
4. ./ configure --with-php-config=/usr/local/php/bin/php-config
5. Compile make
6. Compile and install make install
7. Modify php.ini extension=/usr /local/***.so
8. Restart php-fpm
--------------------- -----------
php optimization nginx optimization mysql optimization

php optimization:
1. Define the class method as static.
2. Try to use single quotes.
3. Modify the number of php-fpm processes.
4. Modify the maximum usable memory of a single script.
5. Large arrays must be released promptly after use.
6. When looping, set the maximum number of loops
7. Do not use @ to shield errors
8. Try to use a large number of PHP built-in functions
9. Use require instead of require_once

nginx optimization:
1. Modify the number of nginx child processes. [Maximum 65535]
2. Enable static cache
3. Modify the number of main processes. It is recommended to specify according to the number of CPUs, usually its multiples (for example, 2 quad-core CPUs are counted as 8)
4. Turn on gzip output [When gzip is turned on, the ob function cannot be used]
5. keepalive_timeout Set connection timeout

mysql optimization:
1. Avoid subqueries
2. Sequential reading
3. Avoid repeated reading and writing
4. Set auto-increment id
5. Avoid using select *
6. Set field types appropriately
7. Separate reading and writing
8. Partition and sub-table
9. Create appropriate indexes
10. Avoid Use the resource-consuming operation null
11. Do not use rand()
12. Try not to use or query
13. Add LIMIT 1 when querying a piece of data
14. Turn on the query cache
15. Conduct a reasonable evaluation of the data in the early stage, and partition and divide the tables.
16. Avoid fuzzy queries using the % prefix
17. Avoid using mysql’s built-in functions
18. Use multiple slaves to solve slow queries Question

How to achieve flash sale?

The number of concurrent flash sales we make is hundreds of thousands, and the version below is hundreds of thousands:

1. Specially for flash sales servers [ps: if the volume is large, say so, if the volume is small No need]
2. Generate static pages. [ ps: If it is still large, you can put this file on cdn ]
3. The countdown and inventory are obtained from the server [Only obtained once in a period of time. After the countdown is over, the server will be requested to see if it has started]
4. Store the database to be sold in redis [key value] stock= 10
5. Set up a redis queue [use list as queue] lpop rpush
6. When the user makes a request, it is judged whether the user has participated in the flash sale or not and writes the user data into the queue. At the same time, the inventory is reduced. 1. If you have participated, you will be prompted to have participated.
ps: This section uses the atomic operation of redid, as well as transaction multi and watch
redis optimistic lock cas ==== is to judge whether the value has changed before setting it
7. Flash sales cannot be carried out when the inventory is reduced by 0
8. Asynchronous script processing queue data [crontab + php file]

If you say it is 10,000-30,000, there is no need to rent a server separately

If you are asked about business-related questions, just adapt to the situation! ! ! !

For example: What should I do if 10 users buy something but don’t pay?
The first statement:
It means that the demand for the product at that time was that there was no problem without paying, and other users could not buy it. What we were doing at the time was discussed with the product, and if the product was normal, users would pay, because Cheaper
The second statement:
will start the next round of flash sales. For example, from Xiaomi, you can continue to buy it after 2 hours! !
Third stop:
Yes. . . .

How to ensure that it is not overbought?
When reducing inventory, it is an atomic operation and uses cas optimistic locking. During the test, there was no overbought situation.

Also, there is no need for a shopping cart during the flash sale. When you click on it, you will queue up.


Q1: How to prevent brushing? of? Generally, there are great discounts during rush sales. If someone maliciously cheats, normal users will lose the opportunity to purchase. For example, if the number of products being snapped up is 1,000, and someone maliciously swipes 900, only 100 will be grabbed by normal users.
After the 900 maliciously grabbed has been verified in the subsequent payment process, the snap-up time may have passed. Even if all the 900 maliciously grabbed are paid successfully, it is unfair to normal users.
In this business scenario, what we do is display the products and issue the right to purchase the products. The actual consumption is generated by a third party. Then, the problem of user fraud needs to be controlled by us and the third-party payment page. After the user obtains the purchase quota through the queuing mechanism, when jumping to a third party, we transfer the encrypted information according to the encryption method agreed with the third party, and the third party only allows the user to pay after successfully decrypting it according to the agreed decryption method. , the encryption and decryption process can contain content with a life cycle. In this way, when a user obtains a product on a high-frequency request payment page, he or she can actually obtain it only through: 1) the encrypted pair; 2) the first time. However, the third party is all about selling goods, so the chance of success of this type of cooperation is low. Malicious brushing will indeed show that the product is out of stock at our business level. As a result, users who want to buy lose the opportunity, but it can ensure that third parties are not damaged. If we want to avoid this brushing situation at our business layer, I think this is a general
anti-SPAM problem. I really don’t know much about this.

Q2: If you want to place brushes accurately, there are many dimensions of judgment and the logic is complicated; contradictory to this, rush buying requires quick response.
Yes, due to the high request pressure and high concurrency of rush purchases for popular products, it is important not to add too much logic and to avoid too many back-end dependencies. The simpler, the better the effect. When we are designing the system, there are many things that cannot be covered by our system alone. We need some pre-requisite modules and capabilities to be ready before our system can run well. It is recommended to build an account system and user consumption records.
Q3: Is reconciliation just to compare the inventory of goods with a third party? Is the amount compared?
Reconciliation is actually a comparison of consumption data. To avoid the situation where our statistics show the consumption of X items with a total value of Y today, the third party gives the consumption of N items with a total value of M. Avoid inconsistencies in amounts, causing problems such as settlement and sharing.
I think the inventory diff problem in your question requires third parties to regularly update the products they provide through the interface of our data layer. In fact, in our product library, the products are not necessarily only allowed to be provided by third parties. We can also allow third parties to reduce products through the interface. For example, if we cooperate with a third party that sells fruits, the third party announced last week that there are 100 products. pieces, but they are selling well offline this week, and there are only 20 pieces left. We should also allow third parties to update to a lower value. But in this way, our
system will be a lot more complicated.

Q4: Anti-brushing to avoid the problem that third-party promotions are not effective.
Yes, the user ID dimension and IP dimension are both effective methods. Look at the specific scenario. For businesses with an account system, the best effect is to use the user ID dimension. Just use storage to record the purchase records of each user for control. Most of the e-commerce websites on the market basically require login for rush-buying business, and limit the number of purchases by a single person for each item. In fact, they store and record the user's consumption, and generate pre-consumption queries again and add code logic to control it.

Q5: Do I need a new verification code for each rush sale event?
Verification code is a Turing test. As long as the test method is good and the verification information generated each time is guaranteed to never appear and is irregular, it is a good verification code.

How to find the one with the most repetitions in massive data

The user's IP is recorded in the website log, and find the IP with the most visits

Assume there are 1kw ID numbers, and their corresponding data. The ID number may be repeated, so you are required to find the ID number that appears the most.

There is a file of 1G size, each line in it is a word, the size of the word does not exceed 16 bytes, and the memory limit is 1M. Returns the 100 most frequent words.

There are 10 files, each file is 1G. Each line of each file stores the user's query. The query of each file may be repeated. You are asked to sort by query frequency.

Bubble sorting:
Principle:
Compare the first number with all numbers, and then encounter a large exchange position, so that the largest one is placed at the end for the first time , and then continue to compare. In the second comparison, the last number will not be compared because it has been determined to be the largest, and so on.

1. Bubble sorting method

 *     思路分析:法如其名,就是像冒泡一样,每次从数组当中 冒一个最大的数出来。 
 *     比如:2,4,1    // 第一次 冒出的泡是4 
 *                2,1,4   // 第二次 冒出的泡是 2 
 *                1,2,4   // 最后就变成这样
Copy after login

Time complexity:
Bubble sorting is a sorting method that trades time for space. The worst case scenario is Change the sequential arrangement into reverse order, or change the reverse sequence into sequential order.


$arr=array(1,43,54,62,21,66,32,78,36,76,39);  
function getpao($arr)
{  
  $len=count($arr);
  //设置一个空数组 用来接收冒出来的泡
  //该层循环控制 需要冒泡的轮数
  for($i=1;$i<$len;$i++)
  { //该层循环用来控制每轮 冒出一个数 需要比较的次数
    for($k=0;$k<$len-$i;$k++)
    {
       if($arr[$k]>$arr[$k+1])
        {
            $tmp=$arr[$k+1];
            $arr[$k+1]=$arr[$k];
            $arr[$k]=$tmp;
        }
    }
  }
  return $arr;
}
Copy after login

2. Selection sort:


http://jingyan.baidu.com/article/f3ad7d0f07516d09c3345b19.html
http://mmm2010.blog.163.com/blog/static/174230348201292273310140/
function select_sort($arr) {
//实现思路 双重循环完成,外层控制轮数,当前的最小值。内层 控制的比较次数
    //$i 当前最小值的位置, 需要参与比较的元素
    for($i=0, $len=count($arr); $i<$len-1; $i++) {
        //先假设最小的值的位置
        $p = $i;
        //$j 当前都需要和哪些元素比较,$i 后边的。
        for($j=$i+1; $j<$len; $j++) {
            //$arr[$p] 是 当前已知的最小值
            if($arr[$p] > $arr[$j]) {
     //比较,发现更小的,记录下最小值的位置;并且在下次比较时,
 // 应该采用已知的最小值进行比较。
                $p = $j;
            }
        }
        //已经确定了当前的最小值的位置,保存到$p中。
 //如果发现 最小值的位置与当前假设的位置$i不同,则位置互换即可
        if($p != $i) {
            $tmp = $arr[$p];
            $arr[$p] = $arr[$i];
            $arr[$i] = $tmp;
        }
    }
    //返回最终结果
    return $arr;
}
3.快速排序法  
function quick_sort($arr) {
    //先判断是否需要继续进行
    $length = count($arr);
    if($length <= 1) {
        return $arr;
    }
    //如果没有返回,说明数组内的元素个数 多余1个,需要排序
    //选择一个标尺
    //选择第一个元素
    $base_num = $arr[0];
    //遍历 除了标尺外的所有元素,按照大小关系放入两个数组内
    //初始化两个数组
    $left_array = array();//小于标尺的
    $right_array = array();//大于标尺的
    for($i=1; $i<$length; $i++) {
        if($base_num > $arr[$i]) {
            //放入左边数组
            $left_array[] = $arr[$i];
        } else {
            //放入右边
            $right_array[] = $arr[$i];
        }
    }
    //再分别对 左边 和 右边的数组进行相同的排序处理方式
    //递归调用这个函数,并记录结果
    $left_array = quick_sort($left_array);
    $right_array = quick_sort($right_array);
    //合并左边 标尺 右边
    return array_merge($left_array, array($base_num), $right_array);
}
Copy after login

4. Insertion sort method

Scenario description:
Followed by bubble sorting, each time The students have tried and failed, but with more and more students, the teacher found that every time he queued up, most of the class was delayed, and said: "We don't need to bubble, it's a bit OUT, let's insert sort today."
At this time, the physical education teacher assumed the responsibility of a mathematics teacher and taught the students a queuing method-insertion sorting.
1. Start with the first classmate as the benchmark, and start with the second classmate moving forward to compare with the first classmate. If he is taller, stay still, if he is lower, change positions
2. The third classmate should start first Compare with the second classmate in front of you. If it is lower, switch with the second one, and then move forward and compare with the first one. If it is lower, switch again. Otherwise, block and no longer compare.
3. Order from front to back Perform step 2, one student comes out one after another, compare each time with the classmate in front of him, find a suitable position to insert, the other students move back to the
suitable position: the previous student is equal to or lower than their own height, and the next student Students are taller than themselves
According to this method, students can find the correct position one by one, no longer need to compare adjacent ones every time, and after finding the position, there is no need to compare to the front...

Insertion sort method idea: Insert the elements to be sorted into the specified position of the array where the sort number has been assumed.

function insert_sort($arr) {
    //区分 哪部分是已经排序好的
    //哪部分是没有排序的
    //找到其中一个需要排序的元素
    //这个元素 就是从第二个元素开始,到最后一个元素都是这个需要排序的元素
    //利用循环就可以标志出来
    //i循环控制 每次需要插入的元素,一旦需要插入的元素控制好了,
    //间接已经将数组分成了2部分,下标小于当前的(左边的),是排序好的序列
    for($i=1, $len=count($arr); $i<$len; $i++) {
        //获得当前需要比较的元素值。
        $tmp = $arr[$i];
        //内层循环控制 比较 并 插入
        for($j=$i-1;$j>=0;$j--) {
   //$arr[$i];//需要插入的元素; $arr[$j];//需要比较的元素
            if($tmp < $arr[$j]) {
                //发现插入的元素要小,交换位置
                //将后边的元素与前面的元素互换
                $arr[$j+1] = $arr[$j];
                //将前面的数设置为 当前需要交换的数
                $arr[$j] = $tmp;
            } else {
                //如果碰到不需要移动的元素
           //由于是已经排序好是数组,则前面的就不需要再次比较了。
                break;
            }
        }
    }
    //将这个元素 插入到已经排序好的序列内。
    //返回
    return $arr;
}
/**
     * 插入排序,默认第一位已经排好序,从第二位开始依次向前比较,确定自己的位置后插入,即前一位小余或等于当前,且后一位大于当前。
     * 插入后,自己新位置后面的元素依次向后移位, 完成一轮插入排序
     * @param arr
     * @return
     */
    public static int[] insertSort(int[] arr) {
        int len = arr.length;
        for (int i = 1; i < len; i++) {
            if (arr[i - 1] > arr[i]) {
                int k = arr[i];
                int j = i;
                while (j > 0 && arr[j - 1] > k) {
                    arr[j] = arr[j - 1];
                    j--;
                }
                arr[j] = k;
            }
        }
        return arr;
    }
Copy after login

1,2,3,4,5,6,7
I want to find 7
I will first take out the middle number 4
to determine if it is The number you are looking for is too small.
Go to the right and search
and then take out all the numbers on the right.
Take out the middle number 6
and find that it is still small.
Continue to look for the number on the right. Array
found 7, ok! ! !

The worst case scenario is that this number does not exist ====

 1 <?php
 2     #二分查找
 3     function binarySearch(Array $arr, $target) {
 4         $low = 0;
 5         $high = count($arr) - 1;
 6         
 7         while($low <= $high) {
 8             $mid = floor(($low + $high) / 2);
 9             #找到元素
10             if($arr[$mid] == $target) return $mid;
11             #中元素比目标大,查找左部
12             if($arr[$mid] > $target) $high = $mid - 1;
13             #重元素比目标小,查找右部
14             if($arr[$mid] < $target) $low = $mid + 1;
15         }
16         
17         #查找失败
18         return false;
19     }
20     
21     $arr = array(1, 3, 5, 7, 9, 11);
22     $inx = binarySearch($arr, 1);
23     var_dump($inx);
24 ?>
Copy after login

安全方面:
xss :跨站脚本攻击
csrf : 跨站请求伪造
Ddos:用很多机器对网址进行请求,把服务器某方面搞挂。
sql注入: 通过关键字或者非法字符的注入,实现一些对数据库一些非正常的操作

最简单的demo :
在用户登陆的时候,用户名和密码的判断,密码后加上 or 1=1

如何防止sql注入:
关键字的过滤
pdo预处理
php 配置文件 php.ini 中的 magic_quotes_gpc选项没有打开,被置为 off
addslashes stripslashes
mysql_real_escape_string
对一些数据类型做强制的校验

如何防止xss攻击?
xss攻击最简单的方式就是通过地址栏输入<script></script>,最简单的列子我们在php在使用一个get的a参数的时候,如何客户端传过来是<script>alert(1)</script>,
这样的话就会在我们的浏览器弹出来1,如果是页面的跳转,或者是一些其它脚本、病毒的话,可能对我们网站的安全造成很大的隐患。

最简单的解决办法
不要相信客户端的任何输入,在程序做严格的判断以及处理
htmlspecialchars进行过滤

csrf :
这个我们在学curl的时候做的模拟登陆就是跨站请求伪造!!!!
最简单的大白话就是:
a网站往b网站请求数据。
加个token防止下就行了,简单,粗暴,有效

Dos和Ddos防止:
阿里云 高防ip
idc机房
放弃一部分请求不处理。


正则方面的问题:

贪婪模式和非贪婪模式的区别:
贪婪模式匹配到内容之后会继续向后匹配
非贪婪模式则不回继续匹配


匹配中文字符的正则表达式: [\u4e00-\u9fa5]
评注:匹配中文还真是个头疼的事,有了这个表达式就好办了
匹配双字节字符(包括汉字在内):[^\x00-\xff]
评注:可以用来计算字符串的长度(一个双字节字符长度计2,ASCII字符计1)
匹配空白行的正则表达式:\n\s*\r
评注:可以用来删除空白行
匹配HTML标记的正则表达式:<(\S*?)[^>]*>.*?|<.*? />
评注:网上流传的版本太糟糕,上面这个也仅仅能匹配部分,对于复杂的嵌套标记依旧无能为力
匹配首尾空白字符的正则表达式:^\s*|\s*$
评注:可以用来删除行首行尾的空白字符(包括空格、制表符、换页符等等),非常有用的表达式
匹配Email地址的正则表达式:\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*
评注:表单验证时很实用
匹配网址URL的正则表达式:[a-zA-z]+://[^\s]*
评注:网上流传的版本功能很有限,上面这个基本可以满足需求
匹配帐号是否合法(字母开头,允许5-16字节,允许字母数字下划线):^[a-zA-Z][a-zA-Z0-9_]{4,15}$
评注:表单验证时很实用
匹配国内电话号码:\d{3}-\d{8}|\d{4}-\d{7}
评注:匹配形式如 0511-4405222 或 021-87888822
匹配腾讯QQ号:[1-9][0-9]{4,}
评注:腾讯QQ号从10000开始
匹配中国邮政编码:[1-9]\d{5}(?!\d)
评注:中国邮政编码为6位数字
匹配身份证:\d{15}|\d{18}
评注:中国的身份证为15位或18位
匹配ip地址:\d+\.\d+\.\d+\.\d+
评注:提取ip地址时有用
匹配特定数字:
^[1-9]\d*$    //匹配正整数
^-[1-9]\d*$   //匹配负整数
^-?[1-9]\d*$   //匹配整数
^[1-9]\d*|0$  //匹配非负整数(正整数 + 0)
^-[1-9]\d*|0$   //匹配非正整数(负整数 + 0)
^[1-9]\d*\.\d*|0\.\d*[1-9]\d*$   //匹配正浮点数
^-([1-9]\d*\.\d*|0\.\d*[1-9]\d*)$  //匹配负浮点数
^-?([1-9]\d*\.\d*|0\.\d*[1-9]\d*|0?\.0+|0)$  //匹配浮点数
^[1-9]\d*\.\d*|0\.\d*[1-9]\d*|0?\.0+|0$   //匹配非负浮点数(正浮点数 + 0)
^(-([1-9]\d*\.\d*|0\.\d*[1-9]\d*))|0?\.0+|0$  //匹配非正浮点数(负浮点数 + 0)
评注:处理大量数据时有用,具体应用时注意修正
匹配特定字符串:
^[A-Za-z]+$  //匹配由26个英文字母组成的字符串
^[A-Z]+$  //匹配由26个英文字母的大写组成的字符串
^[a-z]+$  //匹配由26个英文字母的小写组成的字符串
^[A-Za-z0-9]+$  //匹配由数字和26个英文字母组成的字符串
^\w+$  //匹配由数字、26个英文字母或者下划线组成的字符串

下面是一些特殊字符:
正则表达式中的特殊字符: (学习参考书-<<精通正则表达式>>)
字符
Meaning: For characters, it usually means literal meaning, indicating that the following characters are special characters without explanation.
For example: /b/ matches the character 'b'. By adding a backslash in front of b, that is, /b/, the character becomes a special character, indicating
matches the dividing line of a word.
Or:
For several characters, it is usually stated that they are special, indicating that the following characters are not special and should be interpreted literally.
For example: * is a special character, matching any number of characters (including 0 characters); for example: /a*/ means matching 0 or more a.
To match a literal *, add a backslash before a; for example: /a*/ matches 'a*'.

Character^
Meaning: Indicates that the matching character must be at the front.
For example: /^A/ does not match the 'A' in "an A," but matches the first 'A' in "An A.".

Character$
Meaning: Similar to ^, matches the last character.
For example: /t$/ does not match the 't' in "eater", but matches the 't' in "eat".

Character*
Meaning: Match the character before * 0 or n times.
For example: /bo*/ matches the 'boooo' in "A ghost booooed" or the 'b' in "A bird warbled", but does not match any characters in "A goat g
runted".

Character +
Meaning: Match the character before the + sign 1 or n times. Equivalent to {1,}.
For example: /a+/ matches the 'a' in "candy" and all the 'a's in "caaaaaaandy.".

Character?
Meaning: Match the character before ? 0 or 1 times.
For example: /e?le?/ matches the 'el' in "angel" and the 'le' in "angle.".

Character.
Meaning: (Decimal point) matches all single characters except newline characters.
For example: /.n/ matches 'an' and 'on' in "nay, an apple is on the tree", but does not match 'nay'.


Character (x)
Meaning: Match 'x' and record the matching value.
For example: /(foo)/ matches and records 'foo' in "foo bar.". The matching substring can be returned
by the elements [1], ..., [n] in the result array, or by the properties $1, ..., $9 of the RegExp object.

Character x|y
Meaning: Match 'x' or 'y'.
For example: /green|red/ matches the 'green' in "green apple" and the 'red' in "red apple.".

Character {n}
Meaning: n here is a positive integer. Matches the first n characters.
For example: /a{2}/ does not match the 'a' in "candy,", but matches all the 'a's in "caandy," and the first two
'a in "caaandy." '.

Character{n,}
Meaning: n here is a positive integer. Matches at least n previous characters.
For example: /a{2,} does not match the 'a' in "candy", but matches all the 'a's in "caandy" and all the 'a's in "caaaaaaandy."

Character {n,m}
Meaning: n and m here are both positive integers. Matches at least n and at most m previous characters.
For example: /a{1,3}/ does not match any character in "cndy", but matches the 'a' in "candy," and the first two characters in "caandy,"
'a' And the first three 'a's in "caaaaaaandy", note: even if there are many 'a's in "caaaaaaandy", only the first three 'a's, that is, "aaa" are matched.

Character[xyz]
Meaning: A list of characters, matching any character in the list. You can specify a range of characters using the hyphen -.
For example: [abcd] is the same as [a-c]. They match the 'b' in "brisket" and the 'c' in "ache".

Character[^xyz]
Meaning: One-character complement, that is, it matches everything except the listed characters. You can use hyphens - to indicate a range of
characters.
For example: [^abc] and [^a-c] are equivalent, they match the 'r' in "brisket" and the 'h' in "chop." at the earliest.

Character
Meaning: Match a space (not to be confused with b)

Character b
Meaning: Match the dividing line of a word, such as a space (not to be confused with)
For example: /bnw/ matches 'no' in "noonday", /wyb/ matches 'ly' in "possibly yesterday."

Character B
Meaning: Match the non-breaking line of a word
For example: /wBn/ matches the 'on' in "noonday", /yBw/ matches the 'in "possibly yesterday." ye'.

Character cX
Meaning: X here is a control character. Matches a string of control characters.
For example: /cM/ matches control-M in a string.

Character d
Meaning: Matches a number, equivalent to [0-9].
For example: /d/ or /[0-9]/ matches '2' in "B2 is the suite number.".

Character D
Meaning: Matches any non-number, equivalent to [^0-9].
For example: /D/ or /[^0-9]/ matches the 'B' in "B2 is the suite number.".

Character f
Meaning: Match a form character

Character n
Meaning: Matches a newline character

character r
Meaning: Matches a carriage return character

character s
Meaning: Matches a single white space character, including space, tab, form feed, newline character, equivalent to [fnrtv].
For example: /sw*/ matches 'bar' in "foo bar.".

Character S
Meaning: Matches a single character except white space, equivalent to [^ fnrtv].
For example: /S/w* matches 'foo' in "foo bar.".

Character t
Meaning: Matches a tab character

character v
Meaning: Matches a leading tab character

character w
Meaning: Matches all numbers and letters as well as underscores, equivalent to [A-Za-z0-9_].
For example: /w/ matches the 'a' in "apple,", the '5' in "$5.28," and the '3' in "3D.".

Character W
Meaning: Matches other characters except numbers, letters and underscores, equivalent to [^A-Za-z0-9_].
For example: /W/ or /[^$A-Za-z0-9_]/ matches the '%' in "50%.".

Character n
Meaning: n here is a positive integer. The value of n that matches the last substring of a regular expression (counting left parentheses).


Problems with php functions:

1. Array function

array_key_exists determines whether the key exists
is_array determines whether it is an array
in_array determines Whether the given value appears in the data
array_count_values ​​determines the number of times the value appears
array_search array search
array_merge array merge
array_map uses a user-defined function for each element of the array
array_change_case changes the array Key case
sort array sorting
array_push Insert one or more elements at the end of the array
array_pop Pop the last element of the array
array_unshift Insert multiple elements at the beginning of the array
array_shift Pop the first element of the array elements
implode array to string
shuffle disrupts the sorting of the array
array_rand randomly removes multiple units from the array
array_chunk splits the array into a new array
array_diff difference set
array_inestsert Intersection
array_flip Exchange key values
array_keys Return all keys of the array
count Calculate the length of the array

2, String function
addcslashes — Add backslashes to some characters in the string Escape characters
addslashes — Escape characters in a string in a specified way
bin2hex — Convert binary data to hexadecimal representation
chop — Alias ​​function of rtrim()
chr — Returns the ASCII code of a character
chunk_split — Splits a string into small chunks according to a certain character length
convert_cyr_string — Converts Cyrillic characters to other characters
convert_uudecode — Decrypts a string
convert_uuencode — Encrypt a string
count_chars — Return the character usage information in a string
crc32 — Calculate the crc32 polynomial of a string
crypt — One-way hash encryption function
echo — Use To display some content
explode — Convert a string into an array using a delimiter
fprintf — Return the data as required and write it directly into the document stream
get_html_translation_table — Return an HTML entity that can be converted
hebrev — Convert a Hebrew-encoded string to visual text
hebrevc — Convert a Hebrew-encoded string to visual text
html_entity_decode — The inverse function of htmlentities () function, convert HTML entities Convert to characters
htmlentities — Convert some characters in the string to HTML entities
htmlspecialchars_decode —The inverse function of the htmlspecialchars() function, convert HTML entities to characters
htmlspecialchars — Convert some characters in the string to HTML entity
implode — Convert an array into a string using a specific delimiter
join — Convert an array into a string, alias of the implode() function
levenshtein — Calculate the difference between two words
localeconv — Obtain number-related format definitions
ltrim — Remove the blanks or specified characters on the left side of the string
md5_file — Encrypt a file with the MD5 algorithm
md5 — Encrypt a string with the MD5 algorithm
metaphone — Determine the pronunciation rules of a string
money_format — Format the output of numbers according to parameters
nl_langinfo — Query language and local information
nl2br — Change the newline character "\ in the string n" is replaced with "
"
number_format — formatted output of numbers according to parameters
ord — converts an ASCII code into a character
parse_str — converts a string in a certain format Convert to variables and values ​​
print — used to output a single value
printf — display the data as required
quoted_printable_decode — encrypt a string into an 8-bit binary string
quotemeta — Escape several specific characters
rtrim — Remove the blanks or specified characters on the right side of the string
setlocale — Set local formats for numbers, dates, etc.
sha1_file — SHA1 a file Algorithm encryption
sha1 — Encrypt a string with SHA1 algorithm
similar_text — Compare two strings and return the number of similar characters that the system considers
soundex — Determine the pronunciation rules of a string
sprintf — Return the data as required, but do not output
sscanf — You can format the string
str_ireplace — Match and replace like the str_replace() function String, but case-insensitive
str_pad — padding on both sides of a string
str_repeat — repeatedly combining strings
str_replace — matching and replacing strings
str_rot13 — adding strings Perform ROT13 encryption processing
str_shuffle — Randomly sort the characters in a string
str_split — Split a string into an array according to the character spacing
str_word_count — Get the English word information in the string
strcasecmp — Compares strings by size, case-insensitive
strchr — Returns part of a string by comparison Alias ​​for the strstr() function
strcmp — Compares strings by size
strcoll – Based on Local settings compare the size of strings
strcspn — Returns the value of the continuous non-matching length of characters
strip_tags — Removes HTML and PHP code in a string
stripcslashes — Anti-escaping addcslashes() function escape Processed string
stripos — Finds and returns the position of the first match, matching is case-insensitive
stripslashes — Unescaped addslashes() function escapes the processed string
stristr — Pass Comparison returns part of a string, case-insensitive
strlen — Gets the encoded length of a string
strnatcasecmp — Compares strings using natural sorting, case-insensitive
strnatcmp — Use natural sorting method to compare the size of strings
strncasecmp — Compare the size of the first N characters of the string, case-insensitive
strncmp — Compare the size of the first N characters of the string
strpbrk — Returns a portion of a string by comparing it
strpos — Finds and returns the position of the first match
strrchr — Returns a portion of a string by comparing it backwards
strrev — Replaces a string All letters inside are arranged in reverse order
strripos - Search from back to front and return the position of the first match, matching is not case sensitive
strrpos - Search from back to front and return the position of the first match
strspn — Matches and returns the value of the length of consecutive occurrences of characters
strstr — Returns a portion of a string by comparison
strtok — Splits a string by a specified number of characters
strtolower — Converts a string To lowercase
strtoupper – Convert a string to uppercase
strtr – Compare and replace strings
substr_compare – Compare strings after interception
substr_count – Count the occurrence of a certain character segment in a string Times
substr_replace — Replace some characters in the string
substr — Truncate the string
trim — Remove the blanks or specified characters on both sides of the string
ucfirst — Replace the given string Convert the first letter of each English word to uppercase
ucwords — Convert the first letter of each English word in the given string to uppercase
vfprintf — Return the data as required and write it directly to the document stream
vprintf — Display the data as required
vsprintf — Return the data as required, but do not output
wordwrap — Split the string according to a certain character length



What do you say about coding standards?

When we wrote the interface, we wrote a unified verification and return

It is required that each file must have its own annotation, each class must have its own annotation, and each method must There are comments. For uncertain needs or problems that may be encountered later, you must add todo

Key logic must be written with comments

When calling external interfaces, you cannot hard-code it in the program, you must do it yourself It is recommended to create a configuration file to facilitate later modification

Database operations must be written in the model, and database operations are not allowed to be written in the C layer.

Variable names must be able to clearly express their meaning.

You must get the interface document before writing the interface.

Private methods must be added_ [Important, it seems that I am also an experienced driver]



Class files are all suffixed with .class.php (here refers to The class library file used internally by ThinkPHP does not represent the class library file loaded externally), use camel case naming, and the first letter is capitalized, such as DbMysql.class.php;

The namespace address and path of the class The address is consistent. For example, the path where the Home\Controller\UserController class is located should be Application/Home/Controller/UserController.class.php;
Ensure that the file naming and calling case are consistent because on Unix-like systems, the size of Writing is sensitive (ThinkPHP will strictly check case even in Windows platform in debugging mode);
The class name is consistent with the file name (including the case mentioned above), for example, the file name of the UserController class is UserController .class.php, the file name of the InfoModel class is InfoModel.class.php,
And the class naming of different class libraries has certain standards;

In addition to functions, configuration files and other class library files Generally, the suffix is ​​.php (there is no requirement for third-party introduction);

函数的命名使用小写字母和下划线的方式,例如 get_client_ip;

方法的命名使用驼峰法,并且首字母小写或者使用下划线“_”,例如 getUserName,_parseType,通常下划线开头的方法属于私有方法;
属性的命名使用驼峰法,并且首字母小写或者使用下划线“_”,例如 tableName、_instance,通常下划线开头的属性属于私有属性;
以双下划线“__”打头的函数或方法作为魔法方法,例如 __call 和 __autoload;

常量以大写字母和下划线命名,例如 HAS_ONE和 MANY_TO_MANY;

配置参数以大写字母和下划线命名,例如HTML_CACHE_ON;

语言变量以大写字母和下划线命名,例如MY_LANG,以下划线打头的语言变量
通常用于系统语言变量,例如 _CLASS_NOT_EXIST_;

对变量的命名没有强制的规范,可以根据团队规范来进行;

ThinkPHP的模板文件默认是以.html 为后缀(可以通过配置修改);

数据表和字段采用小写加下划线方式命名,并注意字段名不要以下划线开头,例
如 think_user 表和 user_name字段是正确写法,类似 _username 这样的数据表字段可能会被过滤。


tp底层看过没有?


1、看过框架的底层没有?
看过tp的数据库驱动相关。 关于配置数据库方面的,在配置文件配置就直接可以使用各种数据库类型,自己简单看了下,主要就是通过一个driver(驱动类)来判断当前连接类
型,然后调用对于的数据库操作类。
ps:如果是要我们自己实现的话,可以借助接口,每个数据库的操作类都需要集成一个接口,然后根据具体的配置去调用每个操作类。 就算后期我修改了数据库的类型,也不
会导致程序需要改动。

2、看过tp的cache类,和数据库类似,修改过redis的cache类,因为tp的redis操作类不支持认证。
主要就是在redis操作类添加了个认证

$this->handler  = new \Redis;
        $options[&#39;timeout&#39;] === false ?
            $this->handler->$func($options[&#39;host&#39;], $options[&#39;port&#39;]) :
            $this->handler->$func($options[&#39;host&#39;], $options[&#39;port&#39;], $options[&#39;timeout&#39;]);
            $this -> handler->auth( C(‘REDIS_AUTH_KEY’) );
Copy after login

3、看过tp的处理异常类
路径 ThinkPHP/library/Think/Think.class.php

主要使用的是php自带的错误处理相关函数

register_shutdown_function 定义PHP程序执行完成后执行的函数
set_error_handler 设置用户自定义的错误处理程序
set_exception_handler 设置自己的异常处理机制

借助 get_last_error获取最后一次报错的信息
根据报错级别可以自定义写日志
这个地方我们在做接口的时候纪录了一些错误日志,帮助我们排查一些问题。
如果要看文件加载以及调用关系可以借助 print_debug_backtrace获取文件加载的顺序

     // 注册AUTOLOAD方法
      spl_autoload_register(&#39;Think\Think::autoload&#39;);      
      // 设定错误和异常处理
      register_shutdown_function(&#39;Think\Think::fatalError&#39;);
      set_error_handler(&#39;Think\Think::appError&#39;);
      set_exception_handler(&#39;Think\Think::appException&#39;);
Copy after login

4、简单看了下tp的命名空间自动记载
框架下的核心类都包含进来了,其他的事借助 spl_register_autoload实现。

The above is the detailed content of PHP interview questions compiled and shared. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template