Replace new lines from PHP to JavaScript - php

Situation is simple:
I post a plain HTML form with a textarea. Then, in PHP, I register a JavaScript function depending on the form's content.
This is done using the following code:
$js = sprintf("window.parent.doSomething('%s');", $this->textarea->getValue());
Works like a charm, until I try to process newlines. I need to replace the newlines with char 13 (I believe), but I can't get to a working solution. I tried the following:
$textarea = str_replace("\n", chr(13), $this->textarea->getValue());
And the following:
$js = sprintf("window.parent.doSomething('%s');", "'+String.fromCharCode(13)+'", $this->textarea->getValue());
Does anyone have a clue as to how I can process these newlines correctly?

You were almost there you just forgot to actually replace the line-breaks.
This should do the trick:
$js = sprintf("window.parent.doSomething('%s');"
, preg_replace(
'#\r?\n#'
, '" + String.fromCharCode(13) + "'
, $this->textarea->getValue()
);

What you meant to do was:
str_replace("\n", '\n', $this->textarea->getValue());
Replace all new line characters with the literal string '\n'.
However, you'd do better to encode it as JSON:
$js = sprintf(
"window.parent.doSomething('%s');",
json_encode($this->textarea->getValue())
);
That will fix quotes as well.

Your problem has already been solved elsewhere in our codebase...
Taken from our WebApplication.php file:
/**
* Log a message to the javascript console
*
* #param $msg
*/
public function logToConsole($msg)
{
if (defined('CONSOLE_LOGGING_ENABLED') && CONSOLE_LOGGING_ENABLED)
{
static $last = null;
static $first = null;
static $inGroup = false;
static $count = 0;
$decimals = 5;
if ($first == null)
{
$first = microtime(true);
$timeSinceFirst = str_repeat(' ', $decimals) . ' 0';
}
$timeSinceFirst = !isset($timeSinceFirst)
? number_format(microtime(true) - $first, $decimals, '.', ' ')
: $timeSinceFirst;
$timeSinceLast = $last === null
? str_repeat(' ', $decimals) . ' 0'
: number_format(microtime(true) - $last, $decimals, '.', ' ');
$args = func_get_args();
if (count($args) > 1)
{
$msg = call_user_func_array('sprintf', $args);
}
$this->registerStartupScript(
sprintf("console.log('%s');",
sprintf('[%s][%s] ', $timeSinceFirst, $timeSinceLast) .
str_replace("\n", "'+String.fromCharCode(13)+'", addslashes($msg))));
$last = microtime(true);
}
}
The bit you are interested in is:
str_replace("\n", "'+String.fromCharCode(13)+'", addslashes($msg))
Note that in your questions' sprintf, you forgot the str_replace...

use
str_replace(array("\n\r", "\n", "\r"), char(13), $this->textarea->getValue());
This should replace all new lines in the string with char(13)

Related

Insert some text after the second forward slash in a php string?

I've been working with this code
<?php
class PerchTemplateFilter_sol_en_cat_path extends PerchTemplateFilter {
public function filterAfterProcessing($value, $valueIsMarkup = false) {
// ORIGINAL STRING: solutions-en/rail-technologies/track-components/name-of-product
$mystring = $value;
$replace = ['solutions-en', '%2F'];
$str = '';
$oldstr = str_replace($replace, $str, $mystring);
$str_to_insert = 'XXX';
$findme = '/';
$pos = strpos($mystring, $findme); // I NEED THIS TO INSERT $str_to_insert AFTER THE SECOND FORWARD SLASH FOUND IN THE ORIGINAL STRING?
$value = substr_replace($oldstr, $str_to_insert, $pos, 0);
return $value;
// $value: /rail-technologies/track-components/XXX/name-of-product
// Insert string at specified position
// https://stackoverflow.com/questions/8251426/insert-string-at-specified-position
}
}
PerchSystem::register_template_filter('sol_en_cat_path', 'PerchTemplateFilter_sol_en_cat_path');
?>
My string is: solutions-en/rail-technologies/track-components/name-of-product
I want to end up with: /rail-technologies/XXX/track-components/name-of-product
XXX is only a placeholder value
I guess I need to do something with $pos to set where I want XXX to be added to the string.
I need to insert after the second forward slash, as the string may contain different text
The code above outputs this string: /rail-technoXXXlogies/track-components/ewosr-switch-lock
I can't seem to figure out how to insert XXX after the second forward slash.
Hope someone can provide some help.
How about explode to array, then implode the first two items.
Join with xxx and implode the rest?
function AddInTheMiddle($start, $where, $what){
$arr = explode("/", $what);
$str = implode("/", array_splice($arr,$start,$where)) . '/xxx/' . implode("/", $arr);;
return $str;
}
$str = 'solutions-en/rail-technologies/track-components/name-of-product';
$str = AddInTheMiddle(1, 2, $str);
https://3v4l.org/m98io
Thank you Andreas, your post gave me the nudge I needed. I did this in the end.
// ORIGINAL $value: solutions-en/rail-technologies/track-components/name-of-product
$str = explode("/", $value);
$value = $str[1] . '/' . 'solutions' . '/' . $str[2] . '/';
return $value;
// Removed: solutions-en
// Added: solutions
// $value: rail-technologies/solutions/track-components/name-of-product
I was able to add the name-of-product to the end of the new string elsewhere in my template.

remove - and make every letter after as capital in the string - PHP [duplicate]

I want to take a string like this: 'this-is-a-string' and convert it to this: 'thisIsAString':
function dashesToCamelCase($string, $capitalizeFirstCharacter = false) {
// Do stuff
return $string;
}
I need to convert "kebab-case" to "camelCase".
No regex or callbacks necessary. Almost all the work can be done with ucwords:
function dashesToCamelCase($string, $capitalizeFirstCharacter = false)
{
$str = str_replace(' ', '', ucwords(str_replace('-', ' ', $string)));
if (!$capitalizeFirstCharacter) {
$str[0] = strtolower($str[0]);
}
return $str;
}
echo dashesToCamelCase('this-is-a-string');
If you're using PHP >= 5.3, you can use lcfirst instead of strtolower.
Update
A second parameter was added to ucwords in PHP 5.4.32/5.5.16 which means we don't need to first change the dashes to spaces (thanks to Lars Ebert and PeterM for pointing this out). Here is the updated code:
function dashesToCamelCase($string, $capitalizeFirstCharacter = false)
{
$str = str_replace('-', '', ucwords($string, '-'));
if (!$capitalizeFirstCharacter) {
$str = lcfirst($str);
}
return $str;
}
echo dashesToCamelCase('this-is-a-string');
This can be done very simply, by using ucwords which accepts delimiter as param:
function camelize($input, $separator = '_')
{
return str_replace($separator, '', ucwords($input, $separator));
}
NOTE: Need php at least 5.4.32, 5.5.16
Overloaded one-liner, with doc block...
/**
* Convert underscore_strings to camelCase (medial capitals).
*
* #param {string} $str
*
* #return {string}
*/
function snakeToCamel ($str) {
// Remove underscores, capitalize words, squash, lowercase first.
return lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $str))));
}
In Laravel use Str::camel()
use Illuminate\Support\Str;
$converted = Str::camel('foo_bar');
// fooBar
this is my variation on how to deal with it. Here I have two functions, first one camelCase turns anything into a camelCase and it wont mess if variable already contains cameCase. Second uncamelCase turns camelCase into underscore (great feature when dealing with database keys).
function camelCase($str) {
$i = array("-","_");
$str = preg_replace('/([a-z])([A-Z])/', "\\1 \\2", $str);
$str = preg_replace('#[^a-zA-Z0-9\-_ ]+#', '', $str);
$str = str_replace($i, ' ', $str);
$str = str_replace(' ', '', ucwords(strtolower($str)));
$str = strtolower(substr($str,0,1)).substr($str,1);
return $str;
}
function uncamelCase($str) {
$str = preg_replace('/([a-z])([A-Z])/', "\\1_\\2", $str);
$str = strtolower($str);
return $str;
}
lets test both:
$camel = camelCase("James_LIKES-camelCase");
$uncamel = uncamelCase($camel);
echo $camel." ".$uncamel;
I would probably use preg_replace_callback(), like this:
function dashesToCamelCase($string, $capitalizeFirstCharacter = false) {
return preg_replace_callback("/-[a-zA-Z]/", 'removeDashAndCapitalize', $string);
}
function removeDashAndCapitalize($matches) {
return strtoupper($matches[0][1]);
}
You're looking for preg_replace_callback, you can use it like this :
$camelCase = preg_replace_callback('/-(.?)/', function($matches) {
return ucfirst($matches[1]);
}, $dashes);
here is very very easy solution in one line code
$string='this-is-a-string' ;
echo str_replace('-', '', ucwords($string, "-"));
output ThisIsAString
Try this:
$var='snake_case';
$ucword= ucword($var,'_');
echo $ucword;
Output:
Snake_Case
remove _ with str_replace
str_replace('_','',$ucword); //SnakeCase
and result
$result='SnakeCase'; //pascal case
echo lcfirst('SnakeCase'); //snakeCase (camel case)
the important thing is the approach here I used snake case and camel case in the example
$string = explode( "-", $string );
$first = true;
foreach( $string as &$v ) {
if( $first ) {
$first = false;
continue;
}
$v = ucfirst( $v );
}
return implode( "", $string );
Untested code. Check the PHP docs for the functions im-/explode and ucfirst.
One liner, PHP >= 5.3:
$camelCase = lcfirst(join(array_map('ucfirst', explode('-', $url))));
The TurboCommons library contains a general purpose formatCase() method inside the StringUtils class, which lets you convert a string to lots of common case formats, like CamelCase, UpperCamelCase, LowerCamelCase, snake_case, Title Case, and many more.
https://github.com/edertone/TurboCommons
To use it, import the phar file to your project and:
use org\turbocommons\src\main\php\utils\StringUtils;
echo StringUtils::formatCase('sNake_Case', StringUtils::FORMAT_CAMEL_CASE);
// will output 'sNakeCase'
Here's the link to the method source code:
https://github.com/edertone/TurboCommons/blob/b2e015cf89c8dbe372a5f5515e7d9763f45eba76/TurboCommons-Php/src/main/php/utils/StringUtils.php#L653
function camelize($input, $separator = '_')
{
return lcfirst(str_replace($separator, '', ucwords($input, $separator)));
}
echo ($this->camelize('someWeir-d-string'));
// output: 'someWeirdString';
Try this ;)
$string = 'this-is-a-string';
$separator = '-';
$stringCamelize = str_replace(
$separator,
'',
lcfirst(
ucwords(
strtolower($string),
$separator
)
)
);
var_dump($stringCamelize); // -> 'thisIsAString'
Alternatively, if you prefer not to deal with regex, and want to avoid explicit loops:
// $key = 'some-text', after transformation someText
$key = lcfirst(implode('', array_map(function ($key) {
return ucfirst($key);
}, explode('-', $key))));
Another simple approach:
$nasty = [' ', '-', '"', "'"]; // array of nasty characted to be removed
$cameled = lcfirst(str_replace($nasty, '', ucwords($string)));
Many good solutions above, and I can provide a different way that no one mention before. This example uses array. I use this method on my project Shieldon Firewall.
/**
* Covert string with dashes into camel-case string.
*
* #param string $string A string with dashes.
*
* #return string
*/
function getCamelCase(string $string = '')
{
$str = explode('-', $string);
$str = implode('', array_map(function($word) {
return ucwords($word);
}, $str));
return $str;
}
Test it:
echo getCamelCase('This-is-example');
Result:
ThisIsExample
Some very good solutions here. I compiled them together for easy c&p
declare(strict_types=1);
/**
* convert kebab-case to PascalCase
*/
function kebabToPascal( string $str ): string {
return str_replace( ' ', '', ucwords( str_replace( '-', ' ', $str ) ) );
}
/**
* convert snake_case to PascalCase
*/
function snakeToPascal( string $str ): string {
return str_replace (' ', '', ucwords( str_replace( '_', ' ', $str ) ) );
}
/**
* convert snake_case to camelCase
*/
function snakeToCamel( string $str ): string {
return lcfirst( snakeToPascal( $str ) );
}
/**
* convert kebab-case to camelCase
*/
function kebabToCamel( string $str): string {
return lcfirst( kebabToPascal( $str ) );
}
echo snakeToCamel( 'snake_case' ). '<br>';
echo kebabToCamel( 'kebab-case' ). '<br>';
echo snakeToPascal( 'snake_case' ). '<br>';
echo kebabToPascal( 'kebab-case' ). '<br>';
echo kebabToPascal( 'It will BREAK on things-like_this' ). '<br>';
In Yii2 you can use yii\helpers\Inflector::camelize():
use yii\helpers\Inflector;
echo Inflector::camelize("send_email");
// outputs: SendEmail
Yii provides a lot of similar functions, see the Yii2 Docs.
function camelCase($text) {
return array_reduce(
explode('-', strtolower($text)),
function ($carry, $value) {
$carry .= ucfirst($value);
return $carry;
},
'');
}
Obviously, if another delimiter than '-', e.g. '_', is to be matched too, then this won't work, then a preg_replace could convert all (consecutive) delimiters to '-' in $text first...
If you use Laravel framework, you can use just camel_case() method.
camel_case('this-is-a-string') // 'thisIsAString'
Here is another option:
private function camelcase($input, $separator = '-')
{
$array = explode($separator, $input);
$parts = array_map('ucwords', $array);
return implode('', $parts);
}
$stringWithDash = 'Pending-Seller-Confirmation';
$camelize = str_replace('-', '', ucwords($stringWithDash, '-'));
echo $camelize;
output: PendingSellerConfirmation
ucwords second(optional) parameter helps in identify a separator to camelize the string.
str_replace is used to finalize the output by removing the separator.
Here is a small helper function using a functional array_reduce approach.
Requires at least PHP 7.0
private function toCamelCase(string $stringToTransform, string $delimiter = '_'): string
{
return array_reduce(
explode($delimiter, $stringToTransform),
function ($carry, string $part): string {
return $carry === null ? $part: $carry . ucfirst($part);
}
);
}
private function dashesToCamelCase($string)
{
$explode = explode('-', $string);
$return = '';
foreach ($explode as $item) $return .= ucfirst($item);
return lcfirst($return);
}
This works for me:
function camelCase($string){
$chunks = preg_split("/\s+|-|_/",$string);
$camel = "";
foreach ($chunks as $idx => $chunk){
if ($idx===0){
$camel = strtolower($chunk);
}else{
$camel .= ucfirst($chunk);
}
}
return $camel;
}
The shortest and most elegant solution would be:
function dashesToCamelCase($string, $capitalizeFirstCharacter = false) {
$result = join("", array_map("ucfirst", explode("-", $string)));
if ($capitalizeFirstCharacter === false) {
return lcfirst($result);
}
return $result;
}
One Line Option
echo str_replace(' ', '', lcfirst(ucwords(str_replace("_", " ", 'facebook_catalog_id_type'))));
//output: facebookCatalogIdType
Try this:
return preg_replace("/\-(.)/e", "strtoupper('\\1')", $string);
This is simpler :
$string = preg_replace( '/-(.?)/e',"strtoupper('$1')", strtolower( $string ) );

Before deploying php files, I want to optimize/encrypt them, how?

When my scripts are done, I want to optimize/convert them to smaller size + its harder to get know what do the files even they are stolen.
$c = file_get_contents('source.php');
$newStr = '';
$commentTokens = array(T_COMMENT);
if (defined('T_DOC_COMMENT'))
$commentTokens[] = T_DOC_COMMENT; // PHP 5
if (defined('T_ML_COMMENT'))
$commentTokens[] = T_ML_COMMENT; // PHP 4
$tokens = token_get_all($c);
foreach ($tokens as $token) {
if (is_array($token)) {
if (in_array($token[0], $commentTokens))
continue;
$token = $token[1];
}
$newStr .= $token;
}
$newStr = str_replace (chr(13), '', $newStr);
$newStr = str_replace (chr(10), '', $newStr);
$newStr = preg_replace('/\s+/', ' ', $newStr);
now $newStr contain the "compressed" stuff. Almost OK, but it kills to much white spaces. If there are white spaces in code like this:
if (true)
{
codeeee();
}
it converts to:
if (true)
{
codeeee();
}
and thats ok. But in case of this:
$a = ' var ';
it does:
$a = ' var ';
which is unwanted. How to do this optimize correctly? Are there any ideas? I almost thinking of renaming class names etc.
With help from this answer I was able to create this regex which trims all whitespace (including line breaks) down to single spaces, but preserves the whitespace between quotes (either ' or ")
preg_replace('/\G(?:"[^"]*"|\'[^\']*\'|[^"\'\s]+)*\K\s+/', ' ', $string);

Convert comma separated string into array

I have a comma separated string, which consists of a list of tags and want to convert it to array to get a link for every tag.
Example:
$string = 'html,css,php,mysql,javascript';
I want to make it like this:
html, css, php, mysql, javascript
So the result will be a string containing comma separated links with a space after each link and with no comma after the last link.
I have this function where $arg = 'html,css,php,mysql,javascript':
function info_get_tags( $arg ) {
global $u;
$tagss = '';
if ( $arg == '' ) {
return '';
} else {
$tags_arr = explode( ',' , $arg );
foreach ( $tags_arr as $tag ) {
$tags = '' . $tag . '';
$tagss .= $tags;
}
return $tagss;
}
}
This script works for me but without commas and spaces and if we add a comma and a space here:
$tags = '' . $tag . ', ';
we get commas and spaces but there will be a trailing comma after the last link.
Just like you exploded you can implode again:
$tags = explode(',', $arg);
foreach ($tags as &$tag) {
$tag = '' . $tag . '';
}
return implode(', ', $tags);
Here's an alternative that uses array_map instead of the foreach loop:
global $u;
function add_html($tag){
return('' . $tag . '');
}
function get_tags($taglist){
$tags_arr = array_map("add_html", explode( ',' , $taglist));
return implode(", " , $tags_arr);
}
Try this short code
$string = 'html,css,php,mysql,javascript';
$string = explode(',', $string);
   foreach( $string as $link){
   echo ''.$link.'';
}
Easiest way is to the html into an array (each tag link is an array element) and then implode on ,...
if ( $arg == '' ) {
return '';
} else {
$tags_arr = explode( ',' , $arg );
$tags = array();
$tagtpl = '%s';
foreach ( $tags_arr as $tag ) {
$url = $u . 'tag/' . $tag . '/';
$tags[] = sprintf($tagtpl, $url, $tag, $tag);
}
return implode(', ', $tags);
}
Try this
$tagss = trim($tagss);
return substr($tagss, 0 , strlen($tagss)-1);
Why not put all tags in an array when you are creating them, and later explode the array and add the commas and spaces between the tags.
foreach ( $tags_arr as $tag ) {
$tags = '' . $tag . '';
$tagss[] = $tags;
}
$tagss = explode(', ', $tagss);
The workaround(!) would be to remove the unwanted trailing characters afterwards:
$tagss = rtrim($tagss, ", ");
This rtrim removes any mix of spaces and commas from the right end of the string.
Btw, you could use str_getcsv instead of explode, which also handles input spaces better.
function info_get_tags($arg)
{
global $u;
if (empty($arg)) return '';
return ltrim(preg_replace('/([^\,]+)/', ' ${1}', $arg));
}
$string = 'html,css,php,mysql,javascript';
puts $string.split(/,/).map { |tag| "#{tag}"}.join(", ")
result:
html, css, php, mysql, javascript
Another solution:
$html = trim(preg_replace('/([^,]+)/', ' \1', $string));
Or if you have to html encode the tags (always smart, since you're creating html from text):
$html = trim(preg_replace_callback('/([^,]+)/', function($match) {
$tag = $match[1];
return ' ' . htmlspecialchars($tag) . '';
}, $string));
So this $string would work too: "tag with space,html,css,php,mysql,javascript"
More regex is always good!

remove a part of a URL argument string in php

I have a string in PHP that is a URI with all arguments:
$string = http://domain.com/php/doc.php?arg1=0&arg2=1&arg3=0
I want to completely remove an argument and return the remain string. For example I want to remove arg3 and end up with:
$string = http://domain.com/php/doc.php?arg1=0&arg2=1
I will always want to remove the same argument (arg3), and it may or not be the last argument.
Thoughts?
EDIT: there might be a bunch of wierd characters in arg3 so my prefered way to do this (in essence) would be:
$newstring = remove $_GET["arg3"] from $string;
There's no real reason to use regexes here, you can use string and array functions instead.
You can explode the part after the ? (which you can get using substr to get a substring and strrpos to get the position of the last ?) into an array, and use unset to remove arg3, and then join to put the string back together.:
$string = "http://domain.com/php/doc.php?arg1=0&arg2=1&arg3=0";
$pos = strrpos($string, "?"); // get the position of the last ? in the string
$query_string_parts = array();
foreach (explode("&", substr($string, $pos + 1)) as $q)
{
list($key, $val) = explode("=", $q);
if ($key != "arg3")
{
// keep track of the parts that don't have arg3 as the key
$query_string_parts[] = "$key=$val";
}
}
// rebuild the string
$result = substr($string, 0, $pos + 1) . join($query_string_parts);
See it in action at http://www.ideone.com/PrO0a
preg_replace("arg3=[^&]*(&|$)", "", $string)
I'm assuming the url itself won't contain arg3= here, which in a sane world should be a safe assumption.
$new = preg_replace('/&arg3=[^&]*/', '', $string);
This should also work, taking into account, for example, page anchors (#) and at least some of those "weird characters" you mention but don't seem worried about:
function remove_query_part($url, $term)
{
$query_str = parse_url($url, PHP_URL_QUERY);
if ($frag = parse_url($url, PHP_URL_FRAGMENT)) {
$frag = '#' . $frag;
}
parse_str($query_str, $query_arr);
unset($query_arr[$term]);
$new = '?' . http_build_query($query_arr) . $frag;
return str_replace(strstr($url, '?'), $new, $url);
}
Demo:
$string[] = 'http://domain.com/php/doc.php?arg1=0&arg2=1&arg3=0';
$string[] = 'http://domain.com/php/doc.php?arg1=0&arg2=1';
$string[] = 'http://domain.com/php/doc.php?arg1=0&arg2=1&arg3=0#frag';
$string[] = 'http://domain.com/php/doc.php?arg1=0&arg2=1&arg3=0&arg4=4';
$string[] = 'http://domain.com/php/doc.php';
$string[] = 'http://domain.com/php/doc.php#frag';
$string[] = 'http://example.com?arg1=question?mark&arg2=equal=sign&arg3=hello';
foreach ($string as $str) {
echo remove_query_part($str, 'arg3') . "\n";
}
Output:
http://domain.com/php/doc.php?arg1=0&arg2=1
http://domain.com/php/doc.php?arg1=0&arg2=1
http://domain.com/php/doc.php?arg1=0&arg2=1#frag
http://domain.com/php/doc.php?arg1=0&arg2=1&arg4=4
http://domain.com/php/doc.php
http://domain.com/php/doc.php#frag
http://example.com?arg1=question%3Fmark&arg2=equal%3Dsign
Tested only as shown.

Categories