Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Dynamically building pattern for regex or ??

Status
Not open for further replies.

csteinhilber

Programmer
Aug 2, 2002
1,291
US

I'm trying to devise a way to remove everything from a string up to and including a given substring. Basically an extension of the stristr() function.

I wrote a custom function like:
Code:
function stristrplus($haystack,$needle){

  // remove everything up to needle
  $haystack=stristr($haystack, $needle);
  // now remove needle as well
  $haystack=substr($haystack, strlen($needle));	

  return $haystack;

}

This works fine... unless $haystack contains CRLF's in it's version of $needle.

Example:
Code:
  $needle = "=end of page=";

  $haystack =" 
Lorem ipsum dolor sit amet,
consectetuer adipiscing elit,
aliquip ex ea commodo.
=end of paragraph=

Lorem ipsum dolor sit amet,
suscipit lobortis nisl ut
aliquip ex ea commodo.
=end of paragraph=

Lorem ipsum dolor sit amet,
consectetuer adipiscing elit,
aliquip ex ea commodo.
=end of paragraph==end of
page=

Lorem ipsum dolor sit amet,
suscipit lobortis nisl ut
aliquip ex ea commodo.
=end of paragraph=";

stristrplus() fails because "=end of \npage=" doesn't equal "=end of page="

I rewriting stristrplus() with a eregi statement, like:

Code:
function stristrplus($haystack,$needle){

  $needle = strReplace(" ","[\s]*",$needle);
  $needle = "[\s\S]*" . $needle;
  // remove everything up to and including needle
  $haystack=eregi_replace($needle, "",$haystack);
  return $haystack;

}

but I can't figure out how to dynamically build the pattern (the $needle = lines above don't work).

Anyone have any ideas? How to fix the above, or any other tacts/directions?

Thanks,
-Carl

Hope it helps,
-Carl
 
Nevermind.
Figured it out.

Switched to preg_replace and used the /s modifier.

Code:
function stristrplus($haystack,$needle){

	$haystack = trim($haystack);
	$haystack = preg_replace("/.*?" . $needle . "/si","", $haystack);

	return $haystack;

}
Hope it helps,
-Carl
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top