简体   繁体   中英

php remove everything after a bracket

I'm trying to save a string and the data is coming in with stuff that I don't want at the end of an array.

["bunch", "of", "stuff"]unwantedtext

I'm struggling with getting rid of everything after the closing bracket. This is my latest attempt. I end up with an empty file.

$toPost = substr($str, 0, strrpos($str, '\]'));

Perhaps my escape isn't working correctly? I've also tried doublequotes.

Here's an update to the original question.

This is my Javascript function:

goalChange = function() {
  var i, key, len, postThis;
  key = void 0;
  postThis = {};
  i = 0;
  len = localStorage.length;
  while (i < len) {
    key = localStorage.key(i);
    postThis[key] = "" + localStorage.getItem(key);
    i++;
  }
  postThis.goals = localStorage.getItem("goals");
  postThis.userid = username;
  return $.ajax({
    url: "goalChange.php",
    type: "POST",
    data: postThis,
    success: function(response, textStatus, jqXHR) {
      return console.log("Yay, the save worked!");
    },
    error: function(jqXHR, textStatus, errorThrown) {
      return console.log("Didn't work so good...");
    }
  });
};

Here's the PHP file:

<?
if ($_POST) {
    $user = $_POST['userid'];  // ADDED THIS LINE AND CHANGED NEXT TO GET STUFF INTO THE USERS OWN FILE
    $logFile = dirname($_SERVER['SCRIPT_FILENAME']) . "/" . $user . ".json";
    if (!file_exists($logFile)) {
        touch($logFile);
        chmod($logFile, 0777);
    }
    $newStr = ($_POST);
    $str = str_replace('\\', '', $newStr);
    $toPost = substr($str, 0, strrpos($str, ']'));
    file_put_contents($logFile, $toPost);
    echo "OK";
    return;
}

I need to use the userid to save the file with the correct name. That's working, but the file is getting the userid added to the end of the array that I want to keep.

Thanks for the help.

try..

$text = '["bunch", "of", "stuff"]unwantedtext';
$text = substr($text,0, strpos($text,"]")+1 );

echo $text;

i don't get it.. you want to check a 'json' file (for example) and ..get only the '[]' stuff?

<?php
$text = '["bunch", "of", "stuff"]unwantedtext ["bunchssdfs", "of", "stuxxxff"]dsfadffs';
preg_match_all("#(\[)(.*?)(\])#isU", $text, $matches);

if( sizeof( $matches ) > 0 ){
    $myMatches = $matches[0];
    echo implode(PHP_EOL,$matches[0]); // show matches..
}

Your question is not entirely clear, but judging by the code, you are trying to save the $_POST variable as a json string.

If that is the case, please don't generate the json manually, use json_encode instead:

if ($_POST) {
    $user = $_POST['userid'];  // ADDED THIS LINE AND CHANGED NEXT TO GET STUFF INTO THE USERS OWN FILE
    $logFile = dirname($_SERVER['SCRIPT_FILENAME']) . "/" . $user . ".json";
    if (!file_exists($logFile)) {
        touch($logFile);
        chmod($logFile, 0777);
    }

    file_put_contents($logFile, json_encode($_POST));

    echo "OK";
}

Please note that you need to check the return value from your ajax call to determine if the save really worked. The success function in your javascript is called when a successfull request to the server was made, regardless of the outcome.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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