Php preg match json

preg match со страницы с расширением json

У меня есть одна страница в формате JSON, и я хочу удалить некоторые данные с этой страницы.
Мне нужно отменить это «значение»: «6fc975cd-bbd4-2daa-fc6b-1e8623f80caf | Антенны & Фильтр товаров | Фильтр товаров »
это моя страница JSON

Это моя функция для preg матча

 public function getcategories( $page = '' ) < $results = array(); preg_match_all( '~/\[value\]\s=>\s(.*?)\s*\[~', $page, $matchall ); debug($matchall);die; if ( !empty( $matchall[1] ) ) < foreach ( $matchall[1] as $single ) < if ( strlen( $single ) >1 ) < $results[] = $single; >> > return $results; > 

И я называю эту функцию здесь

function checkpage( $page = '' ) < $vars_all_array = $this->getvarsallfrompage( $page ); $get_api_url = $this->catspostreq($page); $post_data = $this->makePostData( $vars_all_array, 0, 25 ); $jsonpage = $this->get_page( $get_api_url, array ('data' => $post_data, 'content-type'=> 'application/x-www-form-urlencoded; charset="UTF-8"; application/json' ) ); $json_decoded = json_decode($jsonpage); $categories = $this->getcategories( $json_decoded ); debug($categories);die; > 

Но что-то не работает хорошо, у меня есть эта ошибка:

preg_match_all () ожидает, что параметр 2 будет строкой, задан массив

Кто-нибудь может мне помочь?

Решение

Вам не нужно делать preg_match_all, чтобы получить значение из $json_decoded , как json_decode() вернет (в случае успеха) отлично читаемый массив или объект.
Таким образом, чтобы получить одно конкретное значение, вы можете получить к нему доступ следующим образом:

$value = $json_decoded['groupByResults'][0]->values[0]->value; 

Так как вы хотите иметь все значения в новом массиве, вы можете просто перебрать значения и передать их в новый массив:

$categories = []; foreach($json_decoded['groupByResults'][0]->values as $item)

Есть встроенные функции массива, которые делают это в одну строку и, возможно, быстрее. Это для иллюстрации того, что вы делаете с данными.

Используя такую ​​функцию array_column () приведет к этой однострочник:

$categories = array_column($json_decoded['groupByResults'][0]->values, "value"); 

Другие решения

В вашем checkpage Функция, которую вы передаете значение json_decode к getcategories функция как параметр, который в большинстве случаев возвращает массив. и ваш getcategories Вы передаете $page параметр в качестве второго параметра preg_match_all

$json_decoded = json_decode($jsonpage); $categories = $this->getcategories( $json_decoded ); 
preg_match_all('~/\[value\]\s=>\s(.*?)\s*\[~', $page, $matchall); 

здесь $ page является результатом json_decode который является массивом. вот почему вы получаете эту ошибку

Источник

php preg_match find difficult JSON from string

Here is a simple way to get your content without needing to use lookarounds:

preg_match('~var vars = (\<.*?\>;)~m', $get, $json_matches); $json_match = $json_matches[1]; print $json_match; 

I am pretty much just matching all of the data between the curly braces from one to the other.

Quixrick 3160

Read More

Just use lookbehind and lookahead:

n-dru 9202

With a positive lookahead and a lazy quantifier (modified according to your comments):

;)>;)~'; preg_match_all($regex, $file, $matches); $code = $matches[1][0]; echo $code; ?> 

See a demo on regex101.com. This works, however it is very slow and error-prone. Is there some other way to get the code in question?

More Answer

  • Create a JSON string from PHP array with possible dictionaries
  • How to find specific character to create array from string using php
  • Find greatest value from json array in php
  • Exclude items from JSON string that is generated from PHP Array
  • find out match word and display the position of it from the array values using php
  • Convert time from JSON string with PHP
  • How to extract json from html string php
  • getting a json string in php from jquery ajax post
  • find failed rows from string using preg_match PHP
  • PHP build a specific JSON string from postgresql Database
  • Issue with Background Events FullCalendar from php script JSON string
  • php return json encoded string from function
  • How do I retrieve key from JSON string in PHP
  • Passing JSON string from iOS application to PHP Webservice
  • Want to find and remove word only from string using — PHP
  • php preg match a string ignoring white space
  • php regex parsing a string to find substrings that match patterns
  • How do you ‘post’ a json string from corona sdk app to php server?
  • Preg match all won’t find the string
  • match date from string php preg_match
  • How to get the value of an element from a multidimensional JSON string array in PHP
  • Extract item from JSON string using PHP
  • PHP how to extract info from json string wtihout knowing the keys
  • PHP — find all all files within directory that match certain string and put in array
  • Building HTML table from JSON object via php URL
  • Parsing JSON from URL with PHP
  • Correct way to pass string from web page, to php and then to Obj-C Command Line Tool
  • How do I call a JSON web service from PHP with parameters and callback?
  • Returning SQL Blob from PHP JSON
  • regex to match 3 parts from a given string
  • Unable to json decode string from json file
  • JSON not parsing in javascript from PHP
  • Callback Javascript function through Json return from PHP
  • cannot send json data from html to php
  • Amazon Connect receive JSON data from Lambda Function and PHP
  • Extract value from PHP JSON object into jQuery
  • Error CURL and PHP reading upcoming JSON from API
  • Find absolute path to image from relative path with PHP
  • How to pass and read string from android to sql using JSON
  • How do I find multiple substrings in a string in php
  • Why the «jQueryUI autocomplete» is not showing json values received from PHP file in autocomplete enabled input field in following scenario?
  • Using PHP script to call json data and from database Grails do slow data fetch
  • JSON parse data in javascript from php
  • PHP variable value from string
  • php getting substring from a string
  • Use regex to extract integer from url in a string with php

More answer with same ag

  • check if function is defined on child class only
  • Attribute doesn’t validate properly in HTML5
  • How to sort an array alphabetically and then give that order to another array?
  • How to check if the mysqli_object has been freed?
  • php — find segments of similar text within a string with php
  • PHP if() does not return true nor calls all elements
  • How to add variable to value of button?
  • Post a Tweet to User’s Account
  • nginx alternative index not working
  • Is there an advantage to using parse_str for optional function parameters vs an array?
  • How to POST NULL value C#
  • Facebook PHP SDK Extracting Access Token
  • Cakephp-3.x: How to change the data type of a selected alias?
  • How to send multiple jQuery datepicker values to a database
  • Email string parsing using regex
  • Add a period to the middle string PHP
  • where to sanatize data client side or server side
  • Can I make php automatically escape HTML chars when using ?
  • cURL POST request works, Guzzle 6 does not
  • how to sort multidimensional array in code igniter
  • url rewrite problem css messing up
  • Undefined offset Notice in basic PHP script
  • Doctrine order by compound expression
  • How to integrate Angular with Symfony
  • referring asp.net dll to php
  • Regexp for preg_replace in PHP
  • Custom validation message ignored in CakePHP 3.0
  • FedEx Api Fatal error: Call to undefined function setEndpoint()
  • php array to javascript objects
  • Multiple @UniqueEntity annotations at one entity
  • How can I pass PayPal IPN callback throw idevaffiliate to a framework?
  • Laravel Eloquent collection attributes
  • How do I stop Firefox from closing my streaming jQuery ajax response?
  • Get five unique random PHP values selected from an array and put them in separate variables
  • Making Form Input Data Lower-case Letters
  • Laravel cannot add foreign key constraint
  • variable incremented inside function has value 1
  • Form submission for different buttons
  • How do i get the javascript status of any browser?
  • Implementing Email Notification
  • Convert CESU-8 to UTF-8 with high performance
  • Pass value of a include to a variable
  • Save large quantity variables
  • Feeding cURL HTML data to AngularJs
  • insert text to sqlite where text have «
  • Comparing 2 strings
  • Can not add data into database using jquery ajax with php
  • mod_fcgid processes and XCache lifetime
  • Disable button after submit PHP
  • What parameters to create REST API using CakePHP

Источник

Читайте также:  Run main method python
Оцените статью