遍历PHP字符串中的每一行 [英] Iterate over each line in a string in PHP

查看:176
本文介绍了遍历PHP字符串中的每一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个允许用户上载文本文件或将文件内容复制/粘贴到文本区域的表格.我可以轻松地区分两者,然后将它们输入的任何一个放入字符串变量中,但是我从那里去哪里呢?

I have a form that allows the user to either upload a text file or copy/paste the contents of the file into a textarea. I can easily differentiate between the two and put whichever one they entered into a string variable, but where do I go from there?

我需要遍历字符串的每一行(最好不要担心不同机器上的换行符),确保它只有一个令牌(没有空格,制表符,逗号等),清理数据,然后生成基于所有行的SQL查询.

I need to iterate over each line of the string (preferably not worrying about newlines on different machines), make sure that it has exactly one token (no spaces, tabs, commas, etc.), sanitize the data, then generate an SQL query based off of all of the lines.

我是一个非常优秀的程序员,所以我知道如何做的一般想法,但是自从我使用PHP以来已经很久了,以至于我一直在寻找错误的东西,因此想出了无用的信息.我遇到的关键问题是我想逐行读取字符串的内容.如果是文件,那将很容易.

I'm a fairly good programmer, so I know the general idea about how to do it, but it's been so long since I worked with PHP that I feel I am searching for the wrong things and thus coming up with useless information. The key problem I'm having is that I want to read the contents of the string line-by-line. If it were a file, it would be easy.

我主要是在寻找有用的PHP函数,而不是一种算法.有什么建议吗?

I'm mostly looking for useful PHP functions, not an algorithm for how to do it. Any suggestions?

推荐答案

preg_split包含文本的变量,并遍历返回的数组:

preg_split the variable containing the text, and iterate over the returned array:

foreach(preg_split("/((\r?\n)|(\r\n?))/", $subject) as $line){
    // do stuff with $line
} 

这篇关于遍历PHP字符串中的每一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆