simple search code in PHP with demo

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Search PHP source code for function & method calls, variables, and more from PHP.

License

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Searching PHP source code made easy

Search PHP source code for function & method calls, variable assignments, classes and more directly from PHP.

composer require permafrost-dev/php-code-search

To search a file, use the search method. Its only parameter may be either a string containing a valid filename or an instance of \Permafrost\PhpCodeSearch\Support\File .

To search a string instead, use the searchCode method.

The search methods return an instance of Permafrost\PhpCodeSearch\Results\FileSearchResults , which has a results property.

Each result is an instance of Permafrost\PhpCodeSearch\Results\SearchResult with the following properties:

  • node — the specific item that was found
    • node->name(): string
    • location->startLine(): int
    • location->endLine(): int
    • snippet->toString(): string

    To search through the code in a string or file, use the Searcher class:

    use Permafrost\PhpCodeSearch\Searcher; $searcher = new Searcher();

    To search a file, use the search method, and the searchCode method to search a string of code.

    $searcher ->functions(['strtolower', 'strtoupper']) ->search('./file1.php'); $searcher ->variables(['/^one[A-Z]$/']) ->searchCode(');

    When searching using any of the available methods, regular expressions can be used by surrounding the name with slashes / , i.e. /test\d+/ .

    To search for variables by name, use the variables method.

    $results = $searcher ->variables(['twoA', '/^one.$/']) ->searchCode('. ' $oneA = "1a";'. ' $oneB = "1b";'. ' $twoA = "2a";'. ' $twoB = "2b";'. ''); foreach($results->results as $result) < echo "Found '$result->node->name()>' on line $result->location->startLine>" . PHP_EOL; >

    To search for function calls or definitions, use the functions method.

    // search for references AND definitions for 'strtolower' and/or 'myfunc' $searcher ->functions(['strtolower', 'myfunc']) ->search('file1.php');

    To search for a method call by name, use the methods method.

    Method call nodes have an args property that can be looped through to retrieve the arguments for the method call.

    $results = $searcher ->methods(['/test(One|Two)/']) ->searchCode('. ' $obj->testOne("hello world 1"); '. ' $obj->testTwo("hello world", 2); '. '' ); foreach($results->results as $result) < echo "Found '$result->node->name()>' on line $result->location->startLine>" . PHP_EOL; foreach($result->node->args as $arg) < echo " argument: '$arg->value>'" . PHP_EOL; > >

    To search for static method or property calls, use the static method.

    Valid search terms are either a class name like Cache , or a class name and a method name like Cache::remember .

    $searcher ->static(['Ray', 'Cache::has', 'Request::$myProperty']) ->search('./app/Http/Controllers/MyController.php');

    To search for either a class definition or a class created by the new keyword, use the classes method.

    $searcher ->classes(['MyController']) ->search('./app/Http/Controllers/MyController.php');

    To search for a variable assignment by variable name, use the assignments method. Note: The $ should be omitted.

    $searcher ->assignments(['myVar']) ->search('./app/Http/Controllers/MyController.php');

    Results without code snippets

    To return search results without associated code snippets, use the withoutSnippets method:

    $searcher ->withoutSnippets() ->functions(['strtolower']) ->search('file1.php');

    Please see CHANGELOG for more information on what has changed recently.

    Please review our security policy on how to report security vulnerabilities.

    The MIT License (MIT). Please see License File for more information.

    About

    Search PHP source code for function & method calls, variables, and more from PHP.

    Источник

    Пишем поиск по сайту на PHP и MySQL

    Сегодня мы напишем собственный поиск по сайту с использованием PHP и MySQL. Первым делом рассмотрим краткий алгоритм.

    Пользователь выполняет POST запрос из формы поиска, этот запрос передается специальному скрипту-обработчику, который должен обработать поисковый запрос пользователя и возвратить результат.

    Сначала скрипт должен обработать должным образом запрос пользователя для обеспечения безопасности, затем выполняется запрос к базе данных, который возвращает в ассоциативном массиве результаты, которые должны будут выводиться на экран. Итак, приступим.

    Для начала создадим форму поиска на нужной нам странице:

    Эта форма и будет отправлять сам поисковый запрос скрипту search.php. Теперь создадим сам скрипт-обработчик.

     if (!mysql_select_db(DB_NAME)) < exit('Cannot select database'); >mysql_query('SET NAMES utf8'); function search ($query) < $query = trim($query); $query = mysql_real_escape_string($query); $query = htmlspecialchars($query); if (!empty($query)) < if (strlen($query) < 3) < $text = '

    Слишком короткий поисковый запрос.

    '; > else if (strlen($query) > 128) < $text = '

    Слишком длинный поисковый запрос.

    '; > else < $q = "SELECT `page_id`, `title`, `desc`, `title_link`, `category`, `uniq_id` FROM `table_name` WHERE `text` LIKE '%$query%' OR `title` LIKE '%$query%' OR `meta_k` LIKE '%$query%' OR `meta_d` LIKE '%$query%'"; $result = mysql_query($q); if (mysql_affected_rows() >0) < $row = mysql_fetch_assoc($result); $num = mysql_num_rows($result); $text = '

    По запросу '.$query.' найдено совпадений: '.$num.'

    '; do < // Делаем запрос, получающий ссылки на статьи $q1 = "SELECT `link` FROM `table_name` WHERE `uniq_id` = '$row[page_id]'"; $result1 = mysql_query($q1); if (mysql_affected_rows() >0) < $row1 = mysql_fetch_assoc($result1); >$text .= '

    href="'.$row1['link'].'/'.$row['category'].'/'.$row['uniq_id'].'" title="'.$row['title_link'].'">'.$row['title'].'

    '.$row['desc'].'

    '; > while ($row = mysql_fetch_assoc($result)); > else < $text = '

    По вашему запросу ничего не найдено.

    '; > > > else < $text = '

    Задан пустой поисковый запрос.

    '; > return $text; > ?>

    Естественно, данные таблиц БД нужно задать собственные. Рассмотрим, что делает эта функция. Первые 4 строчки обрабатывают запрос, чтобы он стал безопасным для базы. Такую обработку нужно делать обязательно, т. к. любая форма на Вашем сайте — это потенциальная уязвимость для злоумышленников.

    Затем идет проверка, не пустой ли запрос. Если запрос пустой, то возвращаем соответствующее сообщение пользователю. Если запрос не пустой, проверяем его на размер.

    Если поисковый запрос имеет длину менее 3 или более 128 символов, также выводим соответствующие сообщения пользователю. Иначе, выполняем запрос к базе данных, который делает выборку идентификатора страницы, ее заголовка, описания, описания ссылки, категорию, если она есть и идентификатор самой статьи, в которой найдены совпадения нужных нам полей с поисковым запросом.

    В данном случае мы делаем сравнение с текстом статьи, ее заголовком, ключевыми словами и описанием. Если ничего не найдено, выводим пользователю сообщение об этом. Если запрос возвратил хотя бы одну запись, выполняем в цикле еще один запрос, который делает выборку из таблицы со страницами ссылку на страницу, на которой находится статья.

    Если у Вас все статьи на одной странице, вы можете опустить этот шаг. После выполнения запроса при каждой итерации цикла в переменную $text Дозаписываем одну найденную статью.

    После завершения цикла, возвращаем переменную $text , Которая и будет выводиться на нашей странице пользователю.

    Теперь осталось на этой же странице search.php сделать вызов этой функции и вывести ее результат пользователю.

    Также вы можете упростить скрипт поиска по Вашему усмотрению. Желательно создать стиль в таблице css для выводимой информации, чтобы выводимая информация смотрелась более красиво и читабельно. Все замечания вопросы по скрипту можете задавать в комментариях.

    Источник

    Simple Search Code In PHP With Demo

    Simple Search Code In PHP With Demo

    In this tutorial we will show you the solution of simple search code in PHP with demo, here simple search code means there are many rows inside a table that are more than 10000 and we have to search for a name.

    For this, we have to create a simple search box, which helps us to access the data which we want. So, to do this let us understand the example given below.

    Step By Step Guide On Simple Search Code In PHP With Demo :-

    There are many ways with help of which we can create a search code in PHP.

    You can directly create a table and insert data in it manually and create a search box to search something or we can also get the help of a database.

    In this article, we are going to get the help of a database. So, let us see how to do this. Before starting this there must be a database and a table already created with some data.

           

    TalkersCode

    Simple search code in PHP with demo

    "/>

    Result


    ">

    .

    ?>
    ?>
    1. As, here we see that in the above example, we show you how HTML and PHP codes are used.
    2. Here, first of all, we create a basic structure of HTML, in which we use which defines the type of document. And next one is our HTML tags. These tags are paired tags and all the data regarding HTML is written inside these tags.
    3. After we use our head tag which is again paired tag and contains the title and meta information of the webpage. The data written inside the head is not shown on the webpage.
    4. Now, next is our title tag which defines the title of the webpage. The tag which has its closing tag is known as a paired tag. So, this is again a paired tag.
    5. Now, next is the body which is the main tag of HTML. The data which we have written inside the body is shown on the webpage. Mostly all tags which are helpful to show data or information on the screen are written under the body tag.
    6. Here, in the above codes we see that we create a database connection and find data on basis of the text which we fill inside the input type text field. With the help of a like query, we can fetch the required data from the database and it will show us.

    Conclusion :-

    At last, in conclusion, here we can say that with the help of this article we can understand how to use simple search code in PHP with help of a demo.

    I hope this tutorial on simple search code in PHP with demo helps you and the steps and method mentioned above are easy to follow and implement.

    Источник

    Читайте также:  Change one value in array php
Оцените статью