Jump to content

preg_replace or something similar


radi8

Recommended Posts

I need help:

I need to take a multi-line string and replace all white space with a '_' and all CR/LF's with something like a '+' (some non-standard character).

 

example: the following text

The quick brown fox

jumped over the lazy dogs back

 

would become:

The_quick_brown_fox+jumped_over_the_lazy_dogs_back

 

I will then need to replace these back to original format at a later time.

 

can some one help me by giving some code samples?

Link to comment
https://forums.phpfreaks.com/topic/53220-preg_replace-or-something-similar/
Share on other sites

I will then need to replace these back to original format at a later time.

 

And how do you propose to tell a legitimate + symbol from a 'fake' newline, or a legitimate underscore from a fake one that has replaced a space?

 

"C++ is a _really_ good progamming language" would get mangled, for example.

 

Perhaps we need to understand your objective (both directions) before offering a solution.

Thank you for the comment, and very good point...

 

The situation is hard to explain in a short page format like this, but I need to take a string and replace all space's and CR/LF's with some other character (combinations like using the \\s and \\r\\n or something).

 

In essence the text is coming from a multi-line text box and is being used as part of a string (a very long string). I am not to worried about the actual characters I use for the replacements at this time, I will find the appropriate ones at a later time. I really need to get the preg_replace, or str_replace to do the job for me and need help with the syntax.

 

any suggestions for finding and replacing the space and CR/LF is appreciated.

Ok, I think that this works, it's crude and is done in 3 steps (I don't know the syntax well enough to do it in one). Ordering is critical. If you do the search on \s first, it strips the CR/LF, so do that test first then the \s test.

$str = $_POST[$post_text1];
$str = preg_replace('/\r\n+/', '*', $str); //cr/lf windows style
$str = preg_replace('/\n+/', '*', $str); // cr/lf 'nix style
$str = preg_replace('/\s+/', '_', $str); // white space

 

thanks for the help.

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.