Am trying to upload files on my laravel project but getting an error
'ErrorException Array to string conversion'
Any help will be much appreciated. Below is the error
ErrorException Array to string conversion
C:\xampp\htdocs\laravel\filesUpload\vendor\laravel\framework\src\Illuminate\Support\Str.php:609
/**
* Replace a given value in the string sequentially with an array.
*
* #param string $search
* #param array<int|string, string> $replace
* #param string $subject
* #return string
*/
public static function replaceArray($search, array $replace, $subject)
{
$segments = explode($search, $subject);
$result = array_shift($segments);
foreach ($segments as $segment) {
$result .= (array_shift($replace) ?? $search).$segment; //line 609
}
return $result;
}
I am currently working on a template class from broculus.
Now I wanted to install PHP into the template using the class. Unfortunately, I am currently failing.
By eval it is certainly not I have established. Now I wanted to ask if you have an idea how I can solve the problem easily.
Link: http://www.broculos.net/2008/03/how-to-make-simple-html-template-engine.html#.WS8jfWjyjIX
In that code I want to get the value of a variable, which is php code.
That code shall be executed.
Example:
$row_1->content = '$name = 'Pagetitle'; echo $name;';
$row->content contains php and complete scripts.
$layout = new Template("template/layout.tpl");
$layout->set("title", $sitename);
$layout->set("content", eval($row_1->content));
Class:
/**
* Simple template engine class (use [#tag] tags in your templates).
*
* #link http://www.broculos.net/ Broculos.net Programming Tutorials
* #author Nuno Freitas <nunofreitas#gmail.com>
* #version 1.0
*/
class Template {
/**
* The filename of the template to load.
*
* #access protected
* #var string
*/
protected $file;
/**
* An array of values for replacing each tag on the template (the key for each value is its corresponding tag).
*
* #access protected
* #var array
*/
protected $values = array();
/**
* Creates a new Template object and sets its associated file.
*
* #param string $file the filename of the template to load
*/
public function __construct($file) {
$this->file = $file;
}
/**
* Sets a value for replacing a specific tag.
*
* #param string $key the name of the tag to replace
* #param string $value the value to replace
*/
public function set($key, $value) {
$this->values[$key] = $value;
}
/**
* Outputs the content of the template, replacing the keys for its respective values.
*
* #return string
*/
public function output() {
/**
* Tries to verify if the file exists.
* If it doesn't return with an error message.
* Anything else loads the file contents and loops through the array replacing every key for its value.
*/
if (!file_exists($this->file)) {
return "Error loading template file ($this->file).<br />";
}
$output = file_get_contents($this->file);
foreach ($this->values as $key => $value) {
$tagToReplace = "[#$key]";
$output = str_replace($tagToReplace, $value, $output);
}
return $output;
}
/**
* Merges the content from an array of templates and separates it with $separator.
*
* #param array $templates an array of Template objects to merge
* #param string $separator the string that is used between each Template object
* #return string
*/
static public function merge($templates, $separator = "\n") {
/**
* Loops through the array concatenating the outputs from each template, separating with $separator.
* If a type different from Template is found we provide an error message.
*/
$output = "";
foreach ($templates as $template) {
$content = (get_class($template) !== "Template")
? "Error, incorrect type - expected Template."
: $template->output();
$output .= $content . $separator;
}
return $output;
}
}
I found a solution using ob_start. In the panel.php I execute the PHP code via eval.
// Ausgabepuffer an
ob_start();
// Skript ausführen
$_GET['panel'] = 1;
include('panel.php');
// Ausgabe aus Puffer holen
$inhalt = ob_get_contents();
// Puffer schließen
ob_end_clean();
//Layout holen
$layout = new Template("template/layout.tpl");
$layout->set("title", $sitename);
$layout->set("content", $inhalt);
What do you think about this?
Es war keine wirkliche Lösung, wie es sich herausgestellt hat.
Versuche nun die Template Engine von Smarty zu nutzen. Weiß jemand wie ich dort PHP im Template darstellen kann?
require '../libs/Smarty.class.php';
$smarty = new Smarty;
$smarty->compile_check = true;
$smarty->debugging = false;
$smarty->assign("Name","Fred Irving Johnathan Bradley Peppergill");
$smarty->assign("Menu","MENU");
$smarty->assign("Content", "echo 'Testinhalt soll angezeigt werden.'; ");
$smarty->display('index.tpl');
I have looked for other results for this case but couldn't fix it myself. I would be thankful if someone can help me with replacing this preg_replace with preg_replace_callback
preg_replace("/[-_]([a-z])/e", "ucfirst('\\1')", ucwords($verb));
<?php
/** #see Zang_Exception **/
require_once 'Exception.php';
/** #see Zang_Schemas **/
require_once 'Schemas.php';
/**
*
* A Zang InboundXML wrapper.
*
* Please consult the online documentation for more details.
* Online documentation can be found at: http://www.zang.io/docs/api/inboundxml/
*
* --------------------------------------------------------------------------------
*
* #category Zang Wrapper
* #package Zang
* #author Nevio Vesic <nevio#zang.io>
* #license http://creativecommons.org/licenses/MIT/ MIT
* #copyright (2012) Zang, Inc. <support#zang.io>
*/
class Zang_InboundXML
{
/**
* InboundXML simple xml element container
*
* #var null|SimpleXmlElement
*/
protected $element;
/**
* Current child pointer. Used for nesting validations
*
* #var string|null
*/
protected $_currentChild = null;
/**
* Constructs a InboundXML response.
*
* #param SimpleXmlElement|array $arg:
* - the element to wrap
* - attributes to add to the element
* - if null, initialize an empty element named 'Response'
*/
public function __construct($arg = null) {
switch (true) {
case $arg instanceof SimpleXmlElement:
$this->element = $arg;
$this->_currentChild = strtolower($arg->getName());
break;
case $arg === null:
$this->element = new SimpleXmlElement('<Response/>');
$this->_currentChild = 'response';
break;
case is_array($arg):
$this->element = new SimpleXmlElement('<Response/>');
$this->_currentChild = 'response';
foreach ($arg as $name => $value) {
$this->_validateAttribute($name, 'response');
$this->element->addAttribute($name, $value);
}
break;
default: throw new Zang_Exception('InboundXML Invalid construction argument');
}
}
/**
* Converts method calls into InboundXML verbs.
*
* #return SimpleXmlElement A SimpleXmlElement
*/
public function __call($verb, array $args) {
/** convert verbs input like-this-one to LikeThisOne **/
$verb = preg_replace("/[-_]([a-z])/e", "ucfirst('\\1')", ucwords($verb));
/** Let's first go check if the verb exists **/
$this->_validateVerb(ucfirst($verb));
/** Let's go validate nesting **/
$this->_validateNesting(ucfirst($verb));
list($noun, $attrs) = $args + array('', array());
if (is_array($noun)) list($attrs, $noun) = array($noun, '');
$child = empty($noun)
? $this->element->addChild(ucfirst($verb))
: $this->element->addChild(ucfirst($verb), $noun);
foreach ($attrs as $name => $value) {
/** Validation of verb attributes **/
$this->_validateAttribute($name, $verb);
$child->addAttribute($name, $value);
}
return new self($child);
}
/**
* Returns the object as XML.
*
* #return string The response as an XML string
*/
public function __toString() {
$xml = $this->element->asXml();
return str_replace(
'<?xml version="1.0" ?>',
'<?xml version="1.0" encoding="UTF-8" ?>',
$xml
);
}
/**
* Validate existance of the verb. Return true if exists, throw exception
* if fails.
*
* #param string $verb
* #throws Zang_Exception
* #return bool
*/
private function _validateVerb($verb) {
$schemas = Zang_Schemas::getInstance();
if(!$schemas->isVerb(ucfirst($verb))) {
$available_verbs = implode(', ', $schemas->getAvailableVerbs());
throw new Zang_Exception(
"Verb '{$verb}' is not a valid InboundXML verb. Available verbs are: '{$available_verbs}'"
);
}
return true;
}
/**
* Validate if previous child allows this verb to be its child.
*
* #param string $verb
* #return boolean
* #throws Zang_Exception
*/
private function _validateNesting($verb) {
$schemas = Zang_Schemas::getInstance();
if(!$schemas->isNestingAllowed(ucfirst($this->_currentChild), ucfirst($verb))) {
$nestable_verbs = implode(', ', $schemas->getNestableByVerbs(ucfirst($this->_currentChild)));
$current_verb = ucfirst($this->_currentChild);
$next_verb = ucfirst($verb);
throw new Zang_Exception(
"InboundXML element '{$current_verb}' does not support '{$next_verb}' element. The following elements are supported: '{$nestable_verbs}'."
);
}
return true;
}
/**
* Validate if attribute of verb exists. If not, throw exception, otherwise, return true.
*
* #param string $attr
* #param string $verb
* #return boolean
* #throws Zang_Exception
*/
private function _validateAttribute($attr, $verb) {
$schemas = Zang_Schemas::getInstance();
if(!$schemas->isValidAttribute($attr, ucfirst($verb))) {
$verb_attribuges = implode(', ', $schemas->getAvailableAttributes(ucfirst($verb)));
throw new Zang_Exception(
"Attribute '{$attr}' does not exist for verb '{$verb}'. Available attributes are: '{$verb_attribuges}'"
);
}
return true;
}
}
It is a bit unclear why you want to use another function. It might be this is because you are upgrading php and the e modifier is not supported any more. And the example code you posted suggest that you are trying to turn hyphen and underscore concatenated expressions into camel case...
Take a look at this simple demonstration:
<?php
$verb = 'this is a simple-test_sentence to convert.';
echo preg_replace_callback(
"/[-_]([a-z]+)/",
function($string) { return ucfirst($string[1]); },
ucwords($verb)
);
The output obviously is:
This Is A SimpleTestSentence To Convert.
Hi i am trying to set a a test to test my database calls. I want to pass a variables in url but cant seem to get it to work.
I wanted to do this
public function testDb()
{
$response = $this->call('GET', '/searchAvailability?keyword=test product');
$content = $response->getContent();
$this->assertEquals('[{"name":"test product"}]',$content );
}
But i keep getting "Undefined variable : keyword" when i try. It works in the browser just not when i run phpunit. Anyone got any ideas on why this is not working thanks.
The answer here is you need to specify the parameters differently in your call method:
$this->call('GET', '/searchAvailability', array('keyword' => 'test product'));
Below is the implementation of Illuminate\Foundation\Testing\TestCase::call method:
/**
* Call the given URI and return the Response.
*
* #param string $method
* #param string $uri
* #param array $parameters
* #param array $files
* #param array $server
* #param string $content
* #param bool $changeHistory
* #return \Illuminate\Http\Response
*/
public function call()
{
call_user_func_array(array($this->client, 'request'), func_get_args());
return $this->client->getResponse();
}
I'm trying to extract branch=z9hG4bKlmrltg10b801lgkf0681.1 from the Via: header of a SIP message. Here is the PHP code I have tried:
preg_match('/.branch=.* + From:/', $msg, $result)
And here is the value of $msg:
"INVITE sip:3310094#mediastream.voip.cabletel.net:5060 SIP/2.0
Via: SIP/2.0/UDP 192.168.50.240:5060;branch=z9hG4bKlmrltg10b801lgkf0681.1
From: DEATON JEANETTE<sip:9123840782#mediastream.voip.cabletel.net:5060>;tag=SDg7j0c01-959bf958-d8f0f4ea-13c4-50029-140b-4d106390-140b"
How can I correct my regex to make this work?
Please parse your SIP messages properly. I find it highly unlikely that you only want the branch ID, you almost certainly want other information about the transaction other than a pseudo-call ID. SIP messages follow a standardised message format used by several other protocols (including HTTP ;-) ) and there are several libraries out there designed for parsing this message format.
To demonstrate how relatively simple and considerably more powerful this is, lets first take a look at the RFC822 message parser classes that I wrote some time ago (although they have been recently improved and updated). These can be used for parsing emails, I also have a few simple HTTP message parser classes that extend from these:
<?php
/**
* Class representing the basic RFC822 message format
*
* #author Chris Wright
* #version 1.1
*/
class RFC822Message
{
/**
* #var array Collection of headers from the message
*/
protected $headers = array();
/**
* #var string The message body
*/
protected $body;
/**
* Constructor
*
* #param array $headers Collection of headers from the message
* #param string $body The message body
*/
public function __construct($headers, $body)
{
$this->headers = $headers;
$this->body = $body;
}
/**
* Get the value of a header from the message
*
* #param string $name The name of the header
*
* #return array The value(s) of the header from the request
*/
public function getHeader($name)
{
$name = strtolower(trim($name));
return isset($this->headers[$name]) ? $this->headers[$name] : null;
}
/**
* Get the message body
*
* #return string The message body
*/
public function getBody()
{
return $this->body;
}
}
/**
* Factory which makes RFC822 message objects
*
* #author Chris Wright
* #version 1.1
*/
class RFC822MessageFactory
{
/**
* Create a new RFC822 message object
*
* #param array $headers The request headers
* #param string $body The request body
*/
public function create($headers, $body)
{
return new RFC822Message($headers, $body);
}
}
/**
* Parser which creates RFC822 message objects from strings
*
* #author Chris Wright
* #version 1.2
*/
class RFC822MessageParser
{
/**
* #var RFC822MessageFactory Factory which makes RFC822 message objects
*/
protected $messageFactory;
/**
* Constructor
*
* #param RFC822MessageFactory $messageFactory Factory which makes RFC822 message objects
*/
public function __construct(RFC822MessageFactory $messageFactory)
{
$this->messageFactory = $messageFactory;
}
/**
* Split a message into head and body sections
*
* #param string $message The message string
*
* #return array Head at index 0, body at index 1
*/
protected function splitHeadFromBody($message)
{
$parts = preg_split('/\r?\n\r?\n/', ltrim($message), 2);
return array(
$parts[0],
isset($parts[1]) ? $parts[1] : null
);
}
/**
* Parse the header section into a normalized array
*
* #param string $head The message head section
*
* #return array The parsed headers
*/
protected function parseHeaders($head)
{
$expr =
'!
^
([^()<>#,;:\\"/[\]?={} \t]+) # Header name
[ \t]*:[ \t]*
(
(?:
(?: # First line of value
(?:"(?:[^"\\\\]|\\\\.)*"|\S+) # Quoted string or unquoted token
[ \t]* # LWS
)*
(?: # Folded lines
\r?\n
[ \t]+ # ...must begin with LWS
(?:
(?:"(?:[^"\\\\]|\\\\.)*"|\S+) # ...followed by quoted string or unquoted tokens
[ \t]* # ...and maybe some more LWS
)*
)*
)?
)
\r?$
!smx';
preg_match_all($expr, $head, $matches);
$headers = array();
for ($i = 0; isset($matches[0][$i]); $i++) {
$name = strtolower($matches[1][$i]);
if (!isset($headers[$name])) {
$headers[$name] = array();
}
$value = preg_replace('/\s+("(?:[^"\\\\]|\\\\.)*"|\S+)/s', ' $1', $matches[2][$i]);
$headers[$name][] = $value;
}
return $headers;
}
/**
* Create a message object from a string
*
* #param string $message The message string
*
* #return RFC822Message The parsed message object
*/
public function parseMessage($message)
{
list($head, $body) = $this->splitHeadFromBody($message);
$headers = $this->parseHeaders($head);
return $this->requestFactory->create($headers, $body);
}
}
Nothing particularly scary there if you ignore the terrifying regex for parsing the headers :-P - seriously though, these classes can be used unmodified for parsing the header sections of emails, the basis of RFC822 formatted messages.
SIP models itself on HTTP, so with a couple of fairly simple modifications to the HTTP message parsing classes we can easily adapt them to SIP. Let's take a look at those - in these classes I have (more or less) done a search for HTTP and replaced it with SIP:
<?php
/**
* Abstract class representing a SIP message
*
* #author Chris Wright
* #version 1.0
*/
abstract class SIPMessage extends RFC822Message
{
/**
* #var string The message protocol version
*/
protected $version;
/**
* Constructor
*
* #param array $headers Collection of headers from the message
* #param string $body The message body
* #param string $version The message protocol version
*/
public function __construct($headers, $body, $version)
{
parent::__construct($headers, $body);
$this->version = $version;
}
/**
* Get the message protocol version
*
* #return string The message protocol version
*/
public function getVersion()
{
return $this->version;
}
}
/**
* Class representing a SIP request message
*
* #author Chris Wright
* #version 1.0
*/
class SIPRequest extends SIPMessage
{
/**
* #var string The request method
*/
private $method;
/**
* #var string The request URI
*/
private $uri;
/**
* Constructor
*
* #param array $headers The request headers
* #param string $body The request body
* #param string $version The request protocol version
* #param string $method The request method
* #param string $uri The request URI
*/
public function __construct($headers, $body, $version, $method, $uri)
{
parent::__construct($headers, $body, $version);
$this->method = $method;
$this->uri = $uri;
}
/**
* Get the request method
*
* #return string The request method
*/
public function getMethod()
{
return $this->method;
}
/**
* Get the request URI
*
* #return string The request URI
*/
public function getURI()
{
return $this->uri;
}
}
/**
* Class representing a SIP response message
*
* #author Chris Wright
* #version 1.0
*/
class SIPResponse extends SIPMessage
{
/**
* #var int The response code
*/
private $code;
/**
* #var string The response message
*/
private $message;
/**
* Constructor
*
* #param array $headers The request headers
* #param string $body The request body
* #param string $version The request protocol version
* #param int $code The response code
* #param string $message The response message
*/
public function __construct($headers, $body, $version, $code, $message)
{
parent::__construct($headers, $body, $version);
$this->code = $code;
$this->message = $message;
}
/**
* Get the response code
*
* #return int The response code
*/
public function getCode()
{
return $this->code;
}
/**
* Get the response message
*
* #return string The response message
*/
public function getMessage()
{
return $this->message;
}
}
/**
* Factory which makes SIP request objects
*
* #author Chris Wright
* #version 1.0
*/
class SIPRequestFactory extends RFC822MessageFactory
{
/**
* Create a new SIP request object
*
* The last 3 arguments of this method are only optional to prevent PHP from triggering
* an E_STRICT at compile time. IMO this particular error is itself an error on the part
* of the PHP designers, and I don't feel bad about about this workaround, even if it
* does mean the signature is technically wrong. It is the lesser of two evils.
*
* #param array $headers The request headers
* #param string $body The request body
* #param string $version The request protocol version
* #param string $method The request method
* #param string $uri The request URI
*/
public function create($headers, $body, $version = null, $method = null, $uri = null)
{
return new SIPRequest($headers, $body, $version, $method, $uri);
}
}
/**
* Factory which makes SIP response objects
*
* #author Chris Wright
* #version 1.0
*/
class SIPResponseFactory extends RFC822MessageFactory
{
/**
* Create a new SIP response object
*
* The last 3 arguments of this method are only optional to prevent PHP from triggering
* an E_STRICT at compile time. IMO this particular error is itself an error on the part
* of the PHP designers, and I don't feel bad about about this workaround, even if it
* does mean the signature is technically wrong. It is the lesser of two evils.
*
* #param array $headers The response headers
* #param string $body The response body
* #param string $version The response protocol version
* #param int $code The response code
* #param string $message The response message
*/
public function create($headers, $body, $version = null, $code = null, $message = null)
{
return new SIPResponse($headers, $body, $version, $code, $message);
}
}
/**
* Parser which creates SIP message objects from strings
*
* #author Chris Wright
* #version 1.0
*/
class SIPMessageParser extends RFC822MessageParser
{
/**
* #var SIPRequestFactory Factory which makes SIP request objects
*/
private $requestFactory;
/**
* #var SIPResponseFactory Factory which makes SIP response objects
*/
private $responseFactory;
/**
* Constructor
*
* #param SIPRequestFactory $requestFactory Factory which makes SIP request objects
* #param SIPResponseFactory $responseFactory Factory which makes SIP response objects
*/
public function __construct(SIPRequestFactory $requestFactory, SIPResponseFactory $responseFactory)
{
$this->requestFactory = $requestFactory;
$this->responseFactory = $responseFactory;
}
/**
* Remove the request line from the message and parse into tokens
*
* #param string $head The message head section
*
* #return array The parsed request line at index 0, the remainder of the message at index 1
*
* #throws \DomainException When the request line of the message is invalid
*/
private function removeAndParseRequestLine($head)
{
// Note: this method forgives a couple of minor standards violations, mostly for benefit
// of some older Polycom phones and for Voispeed, who seem to make stuff up as they go
// along. It also treats the whole line as case-insensitive even though methods are
// officially case-sensitive, because having two different casings of the same verb mean
// different things makes no sense semantically or implementationally.
// Side note, from RFC3261:
// > The SIP-Version string is case-insensitive, but implementations MUST send upper-case
// Wat. Go home Rosenberg, et. al., you're drunk.
$parts = preg_split('/\r?\n/', $head, 2);
$expr =
'#^
(?:
([^\r\n \t]+) [ \t]+ ([^\r\n \t]+) [ \t]+ SIP/(\d+\.\d+) # request
|
SIP/(\d+\.\d+) [ \t]+ (\d+) [ \t]+ ([^\r\n]+) # response
)
$#ix';
if (!preg_match($expr, $parts[0], $match)) {
throw new \DomainException('Request-Line of the message is invalid');
}
if (empty($match[4])) { // request
$requestLine = array(
'method' => strtoupper($match[1]),
'uri' => $match[2],
'version' => $match[3]
);
} else { // response
$requestLine = array(
'version' => $match[4],
'code' => (int) $match[5],
'message' => $match[6]
);
}
return array(
$requestLine,
isset($parts[1]) ? $parts[1] : ''
);
}
/**
* Create the appropriate message object from a string
*
* #param string $message The message string
*
* #return SIPRequest|SIPResponse The parsed message object
*
* #throws \DomainException When the message string is not valid SIP message
*/
public function parseMessage($message)
{
list($head, $body) = $this->splitHeadFromBody($message);
list($requestLine, $head) = $this->removeAndParseRequestLine($head);
$headers = $this->parseHeaders($head);
if (isset($requestLine['uri'])) {
return $this->requestFactory->create(
$headers,
$body,
$requestLine['version'],
$requestLine['method'],
$requestLine['uri']
);
} else {
return $this->responseFactory->create(
$headers,
$body,
$requestLine['version'],
$requestLine['code'],
$requestLine['message']
);
}
}
}
Seems like a lot of code just for extracting one header value, doesn't it? Well, it is. But that's not just what it does. It parses the whole message into a data structure that provides easy access to any number of bits of information, allowing for (more or less) anything that the standards can throw at you.
So, lets take a look at how you would actually use it:
// First we create a parser object
$messageParser = new SIPMessageParser(
new SIPRequestFactory,
new SIPResponseFactory
);
// Parse the message into an object
try {
$message = $messageParser->parseMessage($msg);
} catch (Exception $e) {
// The message parsing failed, handle the error here
}
// Get the value of the Via: header
$via = $message->getHeader('Via');
// SIP is irritatingly non-specific about the format of branch IDs. This
// expression matches either a quoted string or an unquoted token, which is
// about all that you can say for sure about arbitrary implementations.
$expr = '/branch=(?:"((?:[^"\\\\]|\\\\.)*)"|(.+?)(?:\s|;|$))/i';
// NB: this assumes the message has a single Via: header and a single branch ID.
// In reality this is rarely the case for messages that are received, although
// it is usually the case for messages before they are sent.
if (!preg_match($expr, $via[0], $matches)) {
// The Via: header does not contain a branch ID, handle this error
}
$branchId = !empty($matches[2]) ? $matches[2] : $matches[1];
var_dump($branchId);
See it working
This answer is almost certainly massively overkill for the problem at hand. However, I would regard it as the right way to approach this problem.
preg_match('/branch=.*/i', $msg, $result);
print_r($result);
Will yield something like:
Array
(
[0] => branch=z9hG4bKlmrltg10b801lgkf0681.1
)
Try this
$str = "INVITE sip:3310094#mediastream.voip.cabletel.net:5060 SIP/2.0
Via: SIP/2.0/UDP 192.168.50.240:5060;branch=z9hG4bKlmrltg10b801lgkf0681.1
From: DEATON JEANETTE<sip:9123840782#mediastream.voip.cabletel.net:5060>;tag=SDg7j0c01-959bf958-d8f0f4ea-13c4-50029-140b-4d106390-140b";
preg_match('/branch=(.*)From:/i', $str, $output);
print_r( $output );
Try this regex. It checks if there's a space or newline after the branch code. The result you want is always stored in $output[0]
$str = "INVITE sip:3310094#mediastream.voip.cabletel.net:5060 SIP/2.0
Via: SIP/2.0/UDP 192.168.50.240:5060;branch=z9hG4bKlmrltg10b801lgkf0681.1 From: DEATON JEANETTE<sip:9123840782#mediastream.voip.cabletel.net:5060>;tag=SDg7j0c01-959bf958-d8f0f4ea-13c4-50029-140b-4d106390-140b";
preg_match('/(branch=.*)( |\r\n)/', $str, $output);
print_r( $output ); // $output[0] is what you need
Example:
http://codepad.viper-7.com/Gj0lWD
You can use a look-ahead assertion like this:
preg_match_all('/.branch=(.*?)(?=^\S|\Z)/sm', $msg, $matches);
Here, (?=^\S|\Z) asserts a new line followed by a non-space (aka folding header) or end-of-subject. This is where the match should end.
Or just match branch= until the end of line:
preg_match_all('/.branch=(.*)/m', $msg, $matches);
Works for headers that are not folded.
See also: Basic rules of HTTP headers