Ответы пользователя по тегу PHP
  • Как правильно разбить одну сроку опираясь на другую?

    @user49981
    $str1 = 'Lorem {val1} dolor sit {val2}, consectetur adipisicing {val3}';
            $str2 = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit';
    
            $words1 = explode(' ', $str1);
            $words2 = explode(' ', $str2);
    
            $items = count($words1);
            $result = [];
    
            for($i = 0; $i< $items; $i++) {
                if(preg_match('/{\w*}/', $words1[$i])) {
                    $result["$words1[$i]"] = $words2[$i];
                }
            }
    
            print_r($result);
    Ответ написан
    1 комментарий
  • Какой валидатор использовать?

    Комментировать
  • Как убрать повторное добавление записи в БД при обновлении страницы?

    @user49981
    function add_comment ($connect) {
        if(formSubmit('form_commentaries') 
             && formValid(['name', 'text'], [VALIDATE_NAME, VALIDATE_TEXT])) {
            $name = $_POST['name'];
            $text = $_POST['text'];
            $sql = "INSERT INTO comments (`name`, `text`) VALUES ('$name', '$text')";
            $result = mysqli_query($connect, $sql);
            return $result;
        }
    }
    
    function formSubmit(string $formName)
    {
        if (array_key_exists($formName, $_POST)) {
            return true;
        }
        return false;
    }
    
    // define('VALIDATE_NAME', '/^(\w{3,12})$/');
    // define('VALIDATE_TEXT', ?);
    function formValid(array $fields, array $filters)
    {
        for ($i = 0; $i < count($filters); $i++) {
            if(!preg_match($filters[$i], filter_input_array(INPUT_POST)[$fields[$i]])) {
                return false;
            };
        }
        return true;
    }
    Ответ написан
    Комментировать
  • PHP, регистрация, проверка полей?

    @user49981
    login.html
    <form action="login.php" method="post">
        <input type="text" name="login" id="login"/>
        <input type="password" name="password"/>
        <input type="text" name="form_login" hidden readonly/>
        <input type="submit">
    </form>


    login.php
    <?php
    
    include 'validation.php';
    include 'database.php';
    include 'functions.php';
    
    if (formSubmit('form_login')) {
        if (formValid(['login', 'password'], [VALIDATE_LOGIN, VALIDATE_PASSWORD])) {
            if(isUserExist('login', 'password')) {
                echo "hi";
            }
        }
    }


    functions.php
    <?php
    function formSubmit(string $formName)
    {
        if (array_key_exists($formName, $_POST)) {
            return true;
        }
        return false;
    }
    
    function formValid(array $fields, array $filters)
    {
        for ($i = 0; $i < count($filters); $i++) {
            if(!preg_match($filters[$i], filter_input_array(INPUT_POST)[$fields[$i]])) {
                return false;
            };
        }
        return true;
    }
    
    function isUserExist($loginPostField, $passwordPostFiled, $allowDisabled = true) {
        $login = filter_input_array(INPUT_POST)[$loginPostField];
        $password = filter_input_array(INPUT_POST)[$passwordPostFiled];
        if(userExistInDatabase($login, $password)) {
            return true;
        }
        return false;
    }
    
    function userExistInDatabase($login, $password)
    {
        $mysqli = new \mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
        if ($mysqli->connect_errno) {
            echo 'error:' . __METHOD__ . " : " . __LINE__; die;
        }
        $sql = "SELECT id FROM users WHERE login = $login AND password = " . password_hash($password, PASSWORD_BCRYPT);
        if (!$result = $mysqli->query($sql)) {
            echo 'error:' . __METHOD__ . " : " . __LINE__; die;
        }
        if ($result->num_rows === 1) {
            return true;
        }
        return false;
    }


    database.php
    <?php
    define('DB_HOST', '...');
    // ...


    validation.php
    <?php
    define('VALIDATE_LOGIN', '/^(\w{3,12})$/');
    // ...
    Ответ написан
    1 комментарий
  • Как составить регулярку?

    @user49981
    preg_replace('/((<span[^>]{0,}>)|(<\/span>))/', "", $html);
    Ответ написан
  • Возможно ли перебрать этот json и вывести?

    @user49981
    $json = '{"109238": [], "t13": ["https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8ceb0f8.jpg"], "t14": ["https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8cec0b4.jpg"], "t16": ["https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8cee086.jpg", "https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8cee4c9.jpg"], "t19": ["https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8cf079c.jpg"], "t21": ["https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8cf2ae5.jpg", "https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8cf2fa0.jpg"], "t28": ["https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8d035a9.jpg", "https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8d03a6c.jpg"], "t37": ["https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8d04c41.jpg", "https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8d05156.jpg", "https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8d05647.jpg"], "t39": ["https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8d05ac3.jpg", "https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8d05ff0.jpg", "https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8d06512.jpg"], "t46": ["https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8d06830.jpg", "https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8d06e15.jpg"], "t49": ["https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8d0716b.jpg"], "t57": ["https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8d0774d.jpg", "https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8d07db3.jpg", "https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8d0840f.jpg"], "t62": ["https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8d08782.jpg", "https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8d08e73.jpg"], "t66": ["https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8d092ec.jpg"], "t69": ["https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8d09849.jpg"], "t71": ["https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8d09e24.jpg", "https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8d0a49a.jpg", "https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8d0aa6a.jpg", "https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8d0afc1.jpg"], "t72": ["https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8d0b351.jpg", "https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8d0b902.jpg", "https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8d0be92.jpg"], "t82": ["https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8d0c263.jpg"], "t87": ["https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8d0c6c0.jpg", "https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8d0cc4a.jpg"], "t99": ["https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8d0ced7.jpg", "https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8d0d3a2.jpg", "https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8d0d8b9.jpg"], "t100": ["https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8ce754d.jpg"], "t107": ["https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8ce7c8d.jpg", "https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8ce812b.jpg"], "t109": ["https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8ce84b6.jpg"], "t121": ["https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8ce8a16.jpg", "https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8ce8ee5.jpg", "https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8ce93ac.jpg"], "t123": ["https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8ce96b5.jpg", "https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8ce9b3f.jpg", "https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8cea00e.jpg", "https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8cea509.jpg"], "t127": ["https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8cea956.jpg", "https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8ceadb3.jpg"], "t135": ["https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8ceb5b2.jpg", "https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8ceba37.jpg", "https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8cebe85.jpg"], "t140": ["https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8cec4f7.jpg", "https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8cec97f.jpg"], "t148": ["https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8cecdaa.jpg", "https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8ced512.jpg"], "t158": ["https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8ced8be.jpg", "https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8cedd88.jpg"], "t166": ["https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8cee774.jpg", "https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8ceec06.jpg"], "t172": ["https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8ceeece.jpg"], "t173": ["https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8cef2c8.jpg", "https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8cef76e.jpg", "https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8cefc14.jpg"], "t182": ["https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8ceffc4.jpg"], "t189": ["https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8cf03a4.jpg"], "t196": ["https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8cf0b44.jpg", "https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8cf0fce.jpg"], "t201": ["https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8cf13ad.jpg", "https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8cf1851.jpg"], "t202": ["https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8cf1c8d.jpg", "https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8cf217b.jpg", "https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8cf26b0.jpg"], "t213": ["https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8cf32d7.jpg", "https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8cf379b.jpg", "https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8cf3c66.jpg", "https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8cf416e.jpg", "https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8d0043e.jpg", "https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8d0095a.jpg"], "t240": ["https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8d00cdd.jpg", "https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8d011a5.jpg"], "t257": ["https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8d01602.jpg", "https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8d01ad3.jpg"], "t268": ["https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8d01eac.jpg", "https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8d02349.jpg"], "t272": ["https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8d02765.jpg"], "t273": ["https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8d02bff.jpg", "https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8d030d2.jpg"], "t284": ["https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8d03e7c.jpg", "https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8d0433b.jpg", "https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8d04812.jpg"], "t2-5": ["https://gdz-ru.com/attachments/images/tasks/000/109/238/0002/5c373b8d20a76.jpg"]}';
    $array = json_decode($json);
    $links = [];
    
    foreach ($array as $key => $ls) {
        foreach($ls as $link) {
            $links[] = "<a href={$link}>{$key}</a>";
        }
    }
    
    print_r($links);
    Ответ написан
    Комментировать
  • Как сложить данные в массиве о одинаковым датам?

    @user49981
    $data = [];
    
        $data["datetime"] = [
          "19.07.2019",
          "19.07.2019",
          "20.07.2019",
        ];
        $data["quantity"] = [
           "3",
           "1",
           "5"
        ];
        
        $resultArray = [];
        foreach($data["datetime"] as $key => $value) {
            if(array_key_exists($data["datetime"][$key], $resultArray)) {
                $resultArray[$data["datetime"][$key]] = $resultArray[$data["datetime"][$key]] + $data["quantity"][$key];
            } else {
                $resultArray[$data["datetime"][$key]] = $data["quantity"][$key];    
            }
            
        }
    
        print_r($resultArray);
    Ответ написан
    2 комментария
  • Фреймворк для команды с нулевым опытом в ООП?

    @user49981
    Ответ написан
    Комментировать
  • Регулярные выражения, почему не работает (.*) - ноль или более символов?

    @user49981
    $str = '
    <p>без атрибутов</p>
    <p align="justify" style="color:red;" class="c1">с атрибутами</p>';
    
    $res = preg_replace('/<p ([^>]{0,}[\s]{0,})>/msU', "<p>", $str);
    echo $res;
    Ответ написан
    Комментировать
  • Как измерить скорость php-функции?

    @user49981
    Допустим, есть некоторый массив из 10 элементов и две функции, for и foreach, очевидно
    O(n)
    Ответ написан
    Комментировать
  • Что кому принадлежит из этих объектов?

    @user49981
    $airplane = new Airplane();
    $airplane->fly();
    
    class Airplayne
    {
        public function __construct(EngineInterface $engine) {}
        
        public function fly()
        {
            $this->engine->enable();
        }
        
        public function addPilots() {}
    }
    Ответ написан
    3 комментария
  • Как в многомерном массиве применить для каждого его значения функцию trim, то бишь убрать в начале и конце пробелы?

    @user49981
    $array = [[" abc "], [" efg ", [ " klm ", [" omp "]]]];
        $resultArray = [];
        foreach (new \RecursiveIteratorIterator(new \RecursiveArrayIterator($array)) as $item) {
            $resultArray[] = trim($item);
        }
        print_r($resultArray);
    Ответ написан
    Комментировать
  • PHP разбить текст на слова, вернуть слова и делители?

    @user49981
    $regex = "([а-яА-Яa-zA-Z0-9]*|[.,-_!?;:'\(\)\"]*)";
            $string = "МАЗ 5551 - популярный белорусский грузовик-самосвал, с самосвальным оборудованием. Он выпускается на минском автомобильном заводе!";
            preg_match_all("/$regex/", $string, $matches);
            $matches = $matches[1];
            array_walk($matches,  function ($value, $key) use (&$matches) {
                if(strlen($matches[$key]) < 1) {
                    unset($matches[$key]);
    
                }
            });
            echo '<pre>';
            print_r($matches);
    Ответ написан
    4 комментария
  • Как составить выцепить координвты с помощью регулярного выражения из gps координат?

    @user49981
    $str1 = '(56.61926920000001, 84.88168339999993):8';
    $str2 = '56.61926920000001, 84.12';
    $str3 = '56.61926920000001, 84';
    
    preg_match_all('/([\d]*[.][\d]*)/', $str1, $matches);
    print_r($matches[1]);
    // [0] => 56.61926920000001
    // [1] => 84.88168339999993
    
    preg_match_all('/([\d]*[.][\d]*)/', $str2, $matches);
    print_r($matches[1]);
    // [0] => 56.61926920000001
    // [1] => 84.12
    
    preg_match_all('/([\d]*[.][\d]*)/', $str3, $matches);
    print_r($matches[1]);
    // [0] => 56.61926920000001
    Ответ написан
    1 комментарий
  • Как получить часть ссылки?

    @user49981
    $url = 'https://vk.com/public33333333';
    $regexp = 'https?:\/\/([^\s]*)';
    preg_match("/$regexp/", $url, $matches);
    print_r($matches[1]);
    Ответ написан
    3 комментария
  • Как найти максимальное значение в массиве сформированным Array_push()?

    @user49981
    $massiv=array();
    array_push($massiv, 6);
    array_push($massiv, 2);
    array_push($massiv, 7);
    $result = $massiv ? max($massiv) : 'empty';
    echo $result; // 7
    Ответ написан
    Комментировать
  • Как протестировать защищенный метод абстрактного класса?

    @user49981
    abstract class AbstractClass
    {
        protected function request($body)
        {
            return Document::TEST_VALUE;
        }
    }
    
    class Document extends AbstractClass
    {
        const TEST_VALUE = 403;
    
        public function handle($params)
        {
            $requestBody = 'body';
            return $this->request($requestBody);
        }
    }
    
    class DocumentTest
    {
        public function testRequest()
        {
            $doc = new Document();
            $result = $this->invokeMethod($doc, 'request', [1]);
            self::assertEquals(Document::TEST_VALUE, $result);
        }
    
        private function invokeMethod(&$object, $methodName, array $parameters = array())
        {
            $reflection = new \ReflectionClass(get_class($object));
            $method = $reflection->getMethod($methodName);
            $method->setAccessible(true);
    
            return $method->invokeArgs($object, $parameters);
        }
    }
    Ответ написан
    Комментировать