简体   繁体   English

PHP中的子字符串或正则表达式

[英]Substring or regular expression in PHP

I have the following string: 我有以下字符串:

\r\n-----------------------------7dbbb1a140240\r\nContent-Disposition: form-data; **name="pceq"\r\n\r\n10154**

How would I go about extracting anything that's in the quote right after name and extract everything after \\r\\n\\r\\n . 我将如何提取名称后引号中的所有内容,并提取\\ r \\ n \\ r \\ n之后的所有内容 So I want to extract pceq and 10154 only. 所以我只想提取pceq10154

BTW the only thing that's static in this string would be "dashes" and "\\r\\nContent-Disposition: form-data;" 顺便说一句,在该字符串中唯一静态的是“破折号”和“ \\ r \\ nContent-Disposition:form-data;”。 Which I can care less, I only care about whatever is right after name (pceq) and only (10154). 我不太在乎,我只在乎名称(pceq)和仅(10154)。

Your help is much appreciated and thanks. 非常感谢您的帮助。

Update: 更新:

I took the stars out (which meant to be their to bold it). 我把星星拿掉了(这意味着要把它们加粗)。

\r\n-----------------------------7dbbb1a140240\r\nContent-Disposition: form-data; name="pceq"\r\n\r\n10154

I like @user635522 and @diEcho approach. 我喜欢@ user635522和@diEcho方法。 Are both answer equal? 答案是否相等? Meanning they'll give the same result? 意味着他们会给出相同的结果吗?

Another thing I forgot to mention is that I would like to replace the entire string that I mentioned with an empty string(""). 我忘记提及的另一件事是,我想用空的string(“”)替换我提到的整个字符串。 So something like preg_replace or replace I guess I need to use to blank it out? 所以像preg_replace或replace之类的东西,我想我需要用它来消除它? What would be the approach for that? 这样做的方法是什么? Thanks a lot for everyone who answered. 非常感谢所有回答的人。

I will prefer to use preg_match if string is stored in $var then 如果字符串存储在$ var中,我将更喜欢使用preg_match

preg_match('/name="(.*)"\r\n\r\n(.*)/', $var, $matches);
echo $matches[1]; // name
echo $matches[2]; // numbers

I would just use strpos for this 我只会为此使用strpos

$searchstr; // the string to be searched

$first = substr($searchstr,strpos($searchstr,"name=")+5,strpos($searchstr,'"\r\n"));
$second = substr($searchstr,strpos($searchstr,"\r\n\r\n")+8); // offset here might be 4?

try this 尝试这个

preg_match('/^name="(.*)"\r\n\r\n(.*)/', $var, $matches);
echo $matches[1]; // name
echo $matches[2]; // numbers

Do not match for the value of the name attribute using /"(.*)"/ as this would match anything between the first and last " it can find, including other ". 不要使用/"(.*)"/来匹配name属性的值,因为这将匹配它可以找到的第一个和最后一个“包括其他”之间的任何内容。

A better approach is using negated character classes like so: /"[^"]*"/ 更好的方法是使用否定字符类,例如: /"[^"]*"/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM